[英]How to count occurrences of a column value per ID in BigQuery
If I have a table like this in BigQuery如果我在 BigQuery 中有这样的表
id success
-------------
01 true
01 true
02 false
02 true
I would like to end up with this:我想结束这个:
id true false
--------------------
01 2 0
02 1 1
I've got this but I wondered if there was a more elegant way to do it?我有这个,但我想知道是否有更优雅的方法来做到这一点?
SELECT
t1.id,
(
SELECT
count(*)
FROM `my_table` t2
WHERE t2.success = true and t2.id = t1.id
) as trueCount,
(
SELECT
count(*)
FROM `my_table` t3
WHERE t3.success = false and t3.id = t1.id
) as falseCount
FROM `my_table` t1
GROUP BY id
Consider conditional aggregation which should work on almost all databases:考虑应该适用于几乎所有数据库的条件聚合:
SELECT
t.id,
SUM(CASE WHEN t.success = true THEN 1 ELSE 0 END) AS trueCount,
SUM(CASE WHEN t.success = false THEN 1 ELSE 0 END) AS falseCount
FROM `my_table` t
GROUP BY t.id
You can try to use condition aggregate function instead of the subquery.您可以尝试使用条件聚合 function 而不是子查询。
SELECT id,
COUNT(CASE WHEN success = true THEN 1 END) trueCount,
COUNT(CASE WHEN success = false THEN 1 END) falseCount
FROM T
GROUP BY id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.