如何计算 BigQuery 中每个 ID 的列值的出现次数
How to count occurrences of a column value per ID in BigQuery
如果我在 BigQuery 中有这样的table
id success
-------------
01 true
01 true
02 false
02 true
我想这样结束:
id true false
--------------------
01 2 0
02 1 1
我知道了,但我想知道是否有更优雅的方法来做到这一点?
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
您可以尝试使用条件聚合函数代替子查询。
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
考虑应该适用于几乎所有数据库的条件聚合:
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
考虑以下 BigQuery 方法
select * from your_table
pivot (count(*) for success in (true, false))
如果应用于您问题中的示例数据 - 输出为
如果我在 BigQuery 中有这样的table
id success
-------------
01 true
01 true
02 false
02 true
我想这样结束:
id true false
--------------------
01 2 0
02 1 1
我知道了,但我想知道是否有更优雅的方法来做到这一点?
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
您可以尝试使用条件聚合函数代替子查询。
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
考虑应该适用于几乎所有数据库的条件聚合:
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
考虑以下 BigQuery 方法
select * from your_table
pivot (count(*) for success in (true, false))
如果应用于您问题中的示例数据 - 输出为