【问题标题】:How to get totals for each age category?如何获得每个年龄类别的总数?
【发布时间】:2019-08-15 17:17:34
【问题描述】:
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;

这张表给了我我想要的东西,但我想要多一行作为所有人和每个类别的总数。如果从上面的代码中按声明删除该组,我可以获得具有正确数字的单行。 有什么办法可以同时满足这两种情况,按饮料分类,并且每个类别的总数都在同一张表中?

【问题讨论】:

  • 您显然在使用 proc-sql,所以我更改了标签。如果这是对 MySQL 的直通查询,您应该清楚。

标签: sql proc-sql


【解决方案1】:

你可以使用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;

【讨论】:

  • 感谢戈登的帮助。
猜你喜欢
  • 1970-01-01
  • 2019-10-04
  • 2021-09-03
  • 2019-05-03
  • 2021-12-08
  • 1970-01-01
  • 1970-01-01
  • 2012-12-03
  • 1970-01-01
相关资源
最近更新 更多