如何获得每个年龄段的总数?

时间:2019-08-15 17:17:34

标签: sql proc-sql

proc sql;
 create table final as select drink,
 count(distinct id) as total_persons,
 count(distinct case when age_cat = '20-25' then id end) as tot_20_25, 
 count(distinct case when age_cat = '25-30' then id end) astot_25_30, 
 count(distinct case when age_cat = '30-35' then id end) as tot_30_35 
 from old_table
 group by drink
 order by total_persons
 quit;

这张桌子给了我我想要的东西,但是我想再增加一行作为所有人员和每个类别的总数。如果从上面的代码中按指令删除该组,则我可以得到具有正确数字的那一行。 是否可以通过饮料将两种情况同时归入同一类别的表中?

1 个答案:

答案 0 :(得分:0)

您可以使用union all

proc sql;
 create table final as
     select drink,
            count(distinct id) as total_persons,
            count(distinct case when age_cat = '20-25' then id end) as tot_20_25, 
            count(distinct case when age_cat = '25-30' then id end) as tot_25_30, 
            count(distinct case when age_cat = '30-35' then id end) as tot_30_35 
     from old_table
     group by drink
     union all
     select 'Total',
            count(distinct id) as total_persons,
            count(distinct case when age_cat = '20-25' then id end) as tot_20_25, 
            count(distinct case when age_cat = '25-30' then id end) as tot_25_30, 
            count(distinct case when age_cat = '30-35' then id end) as tot_30_35 
     from old_table;