如何获得每个年龄段的总数?
How to get totals for each age category?
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;
这个 table 给了我我想要的,但我想要多一行作为所有人的总数,如果从上面删除,每个 category.I 可以获得正确数字的单行通过声明对组进行编码。
有什么方法可以同时处理两种情况,按饮料,并且每个类别的总计 table 相同?
您可以使用 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;
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;
这个 table 给了我我想要的,但我想要多一行作为所有人的总数,如果从上面删除,每个 category.I 可以获得正确数字的单行通过声明对组进行编码。 有什么方法可以同时处理两种情况,按饮料,并且每个类别的总计 table 相同?
您可以使用 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;