tar*_*ing 0 sql google-bigquery
如果我在 BigQuery 中有一个这样的表
id success
-------------
01 true
01 true
02 false
02 true
Run Code Online (Sandbox Code Playgroud)
我想以此结束:
id true false
--------------------
01 2 0
02 1 1
Run Code Online (Sandbox Code Playgroud)
我已经得到了这个,但我想知道是否有更优雅的方法来做到这一点?
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
Run Code Online (Sandbox Code Playgroud)
考虑条件聚合,它应该适用于几乎所有数据库:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2398 次 |
| 最近记录: |