SAS-SQL步
2017-03-31 09:27阅读:
SAS对熟悉SQL语句的人来说特别容易学习,因为SAS中有一个Proc
sql过程,支持标准的SQL语句,基本可以替代大多数data步语句,能够进行表关联、统计汇总等操作。
1.1.
Proc
sql选项
Proc
sql后面有多个可选选项,可以对整个sql过程进行控制。Inobs=表示读入的观测数;outobs=表示输出的观测数;loops=表示限制循环数;noexec用来检查语法正确性,不会执行语句,与validate语句相同;feedback用来显示选择列的信息。
1.2.
Select语句
Select语句是Proc
sql步中最基本的语句,主要语句结构就是select…from…;可
以为每个表指定一个别名(alias),如a、b、c等,主要是为了方便后面的简写;*代表选择所有;可以通过format、informat、length、label
等指定列的格式。
Proc sql
outobs=n;
Create table table_name
as
Select (distinct) row_names
from table_name_1
Where conditions
Order by row_name_1;
Quit;
Proc
sql;
Select x1,x1*x2 as
new,(calculated new*x3) from
test;
Quit;
Proc sql
outobs=100;
Select user_id,arpu
format=8.2
label='消费'
from other.train;
Quit;
1.3.
SQL表连接
表的连接是Proc
sql中使用最多的操作,主要是求并集、交集、关联字段、纵向合
并等,关键词是inner join、left
join、right join、cross
join等,跟data步的merge作用相同。
关键词
|
含义
|
Inner join
|
求两个数据集的交集,相当于data步的merge…..if a and
b,也相当于proc sql….where
proc
sql;
create table all_1308
as
select * from
zaiwang_1308 inner join
tc_1308
on
zaiwang_1308.user_id=tc_1308.user_id;
quit;
|
Left Join
|
以左边的数据集为基准,没有匹配项时返回“.”,相当于merge…if
a
proc
sql;
create table all_1308
as
select * from
zaiwang_1308 left join
tc_1308
on
zaiwang_1308.user_id=tc_1308.user_id;
quit;
|
Right join
|
以右边的数据集为基准,没有的用“.”代替,相当于merge…if
b
proc
sql;
create table all_1308
as
select * from
zaiwang_1308 right join
tc_1308
on
zaiwang_1308.user_id=tc_1308.user_id;
quit;
|
Full join
|
求两个数据集的并集,相当于data步的merge…..if a or
b
proc
sql;
create table all_1308
as
select * from
zaiwang_1308 full join
tc_1308
on
zaiwang_1308.user_id=tc_1308.user_id;
quit;
|
Cross join
|
求两个数据集的交集,相当于data步的merge…..if a and
b
|
Union (all)
|
针对结构完全相同(字段数和字段顺序)的数据集求并集,相当于data步的set,all表示不去掉重复观测项
proc
sql;
create table all_1308
as
select * from
zaiwang_1308 union
tc_1308;
quit;
|
Except (all)
|
针对结构完全相同的数据集求,求在前一个数据集中,但不在后一个数据集中的观测
proc
sql;
create table all_1308
as
select * from
zaiwang_1308 except
tc_1308;
quit;
|
Intersect (all)
|
针对结构完全相同的数据集求,求两个数据集的交集
proc
sql;
create table all_1308
as
select * from
zaiwang_1308 intersect
tc_1308;
quit;
|
1.4.
Case
when语句
Case when语句相当于data步中的if
then语句,主要用于字段分层、生成新的
字段等,语法格式为Case…when…else或case when
…else…。
Proc
sql;
Create table test
as
Select a.*,case
when
market='校园'
then 1
when
market='城市'
then 2
else
3 end as
market_flag
From other.train a;
Quit;
Proc
sql;
Create table test
as
Select a.*,case market
when '校园'
then 1
when
'城市' then
2
else
3 end as
market_flag_1
From other.train a;
Quit;
1.5.
Order
by语句
Order
by语句主要是用来对观测进行排序,可以对选中的列、计算后的列、选中
列的顺序、没有被选中的列进行排序,默认为升序排列(asc),用desc选项申明降序排列,order
by语句与proc步中的proc
sort一样,order
by只改变输出数据集的顺序,不改变源数据集的顺序。
Proc sql
outobs=100;
Select user_id,arpu from
other.train
Order by arpu
desc;*先选出100个输出观测,在进行降序排列;
Quit;
Proc sql
outobs=100;
Select user_id,arpu*mou as
arpu_mou from
other.train
Order by arpu_mou
desc;*对计算的列排序;
Quit;
Proc sql
outobs=100;
Select user_id,arpu,mou,gprs
from other.train
Order by 4
desc;*对选中列的顺序排列;
Quit;