如何将PROC SQL COUNT生成的统计结果合并为单个表格?
合并PROC SQL COUNT结果的两种实用方法
刚好我经常处理这类需求,给你分享两种实用方案,不管是4个表还是更多表都能轻松套用:
方法一:一次性统计+合并(推荐)
如果还没单独生成每个表的统计结果,直接在单个PROC SQL语句里完成统计和合并,一步到位效率最高。核心是用UNION ALL把每个表的COUNT结果拼接成一行行的记录,同时给每个结果加个表名字段,方便后续识别:
proc sql; create table combined_counts as -- 第一个表的统计,指定表名标识 select 'table1' as table_name, count(*) as obs_count from table1 union all -- 用UNION ALL而非UNION,避免不必要的去重,速度更快 select 'table2' as table_name, count(*) as obs_count from table2 union all select 'table3' as table_name, count(*) as obs_count from table3 union all select 'table4' as table_name, count(*) as obs_count from table4; quit;
执行后combined_counts就是规整的表格:每行对应一个表,包含table_name(表名)和obs_count(观测数)两列。
方法二:合并已有的单独统计结果
如果已经分别生成了每个表的统计临时表(比如table1_count、table2_count,每个表只有一行一列的观测数),可以根据你想要的最终格式选择合并方式:
方式A:转成行式表格(和方法一结果一致)
用UNION ALL把每个临时表的结果转成带表名的行,再拼接:
proc sql; create table combined_counts as select 'table1' as table_name, table1_obs as obs_count from table1_count union all select 'table2' as table_name, table2_obs as obs_count from table2_count union all select 'table3' as table_name, table3_obs as obs_count from table3_count union all select 'table4' as table_name, table4_obs as obs_count from table4_count; quit;
方式B:合并成列式表格(一行多列)
如果想把所有表的观测数放在同一行,用DATA步的MERGE或者PROC SQL交叉连接即可:
-- DATA步方式 data combined_counts; merge table1_count table2_count table3_count table4_count; run; -- PROC SQL方式 proc sql; create table combined_counts as select a.table1_obs, b.table2_obs, c.table3_obs, d.table4_obs from table1_count a, table2_count b, table3_count c, table4_count d; quit;
通用批量处理技巧(适合大量表)
如果要统计的表数量很多,手动写每个SELECT太麻烦,可以用SAS宏循环自动生成代码。比如先指定要统计的表名列表,宏会自动完成统计和合并:
%macro count_and_combine(tables); proc sql; create table combined_counts as %let total_tables = %sysfunc(countw(&tables)); %do i = 1 %to &total_tables; %let current_table = %scan(&tables, &i); select "¤t_table" as table_name, count(*) as obs_count from ¤t_table %if &i < &total_tables %then union all; -- 最后一行不加UNION ALL %end; ; quit; %mend; -- 调用宏,传入要统计的表名(空格分隔) %count_and_combine(table1 table2 table3 table4);
注意事项
- 优先用
UNION ALL:和UNION相比,它不会对结果去重,执行速度更快(我们的计数结果不需要去重); - 必须加表名字段:否则合并后无法区分每个数值对应哪个表;
- 利用字典表批量获取表名:如果要统计某个库下的所有表,可以查询
dictionary.tables获取表名列表,再传入宏中,完全自动化处理。
内容的提问来源于stack exchange,提问作者user16461886
相关产品推荐
相关产品推荐

