SQL:如何获取 table 中每个不同行的过滤计数?
SQL: How do I get a filtered count for each distinct row in a table?
注意:这与 "I want a count for each distinct row in a table" 已被多次回答的问题不同。这是一个过滤计数,因此查询的计数部分需要一个更复杂的 WHERE 子句。考虑这个数据集:
customer_id | user_id | age
-----------------------------
1 | 932 | 20
1 | 21 | 3
1 | 2334 | 32
2 | 232 | 10
2 | 238 | 28
3 | 838 | 39
3 | 928 | 83
4 | 842 | 12
我想查询此 table 并了解每个不同 customer_id 的 13 岁以上用户的数量。所以结果将是:
customer_id | over_13_count
-----------------------------
1 | 2
2 | 1
3 | 2
4 | 0
我试过类似的东西,但它永远运行,所以我认为我做错了:
SELECT DISTINCT customer_id,
(SELECT COUNT(*) FROM mytable AS m2 WHERE m2.customer_id = m1.customer_id AND age > 13) AS over_13_count
FROM mytable AS m1
ORDER BY customer_id
只使用条件聚合:
SELECT customer_id,
SUM(CASE WHEN age > 13 THEN 1 ELSE 0 END) asover_13_count
FROM mytable m1
GROUP BY customer_id
注意:这与 "I want a count for each distinct row in a table" 已被多次回答的问题不同。这是一个过滤计数,因此查询的计数部分需要一个更复杂的 WHERE 子句。考虑这个数据集:
customer_id | user_id | age
-----------------------------
1 | 932 | 20
1 | 21 | 3
1 | 2334 | 32
2 | 232 | 10
2 | 238 | 28
3 | 838 | 39
3 | 928 | 83
4 | 842 | 12
我想查询此 table 并了解每个不同 customer_id 的 13 岁以上用户的数量。所以结果将是:
customer_id | over_13_count
-----------------------------
1 | 2
2 | 1
3 | 2
4 | 0
我试过类似的东西,但它永远运行,所以我认为我做错了:
SELECT DISTINCT customer_id,
(SELECT COUNT(*) FROM mytable AS m2 WHERE m2.customer_id = m1.customer_id AND age > 13) AS over_13_count
FROM mytable AS m1
ORDER BY customer_id
只使用条件聚合:
SELECT customer_id,
SUM(CASE WHEN age > 13 THEN 1 ELSE 0 END) asover_13_count
FROM mytable m1
GROUP BY customer_id