让我们假设我有一个表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。
您不需要在GROUP BY
子句中包含country
,因为您需要计数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;