如何以宽格式获得与一组不同的计数结果的不同?

时间:2018-07-30 16:21:59

标签: sql presto

让我们假设我有一个像这样的表t1

week | id | country
-----+----+--------
1    | 1  | D      
1    | 2  | E      
1    | 3  | E      
2    | 1  | D      
2    | 4  | D      

我的目标是获得一个表格t2,该表格为每个国家/地区报告不同ID的数量:

week | distinct_ids_D | distinct_ids_E
-----+----------------+---------------
1    | 1              | 2
2    | 2              | 0

我的想法是做一个普通的group_by

SELECT week, country, COUNT(DISTINCT id) count FROM t1 GROUP BY week, country

但这给了我t2长格式:

week | country | count
-----+---------+--------
1    | D       | 1      
1    | E       | 2      
2    | D       | 2      
2    | E       | 0      

如何获取宽格式?解决方案应该在Presto中。

1 个答案:

答案 0 :(得分:0)

您不需要在country子句中包含GROUP BY,因为您要计算e的国家/地区

SELECT week, 
       COUNT(DISTINCT id) as distinct_ids_D,
       COUNT(DISTINCT CASE WHEN country = 'E' then country END) as distinct_ids_E
FROM t1 
GROUP BY week;