[英]SQL: How do I get a filtered count for each distinct row in a table?
Note: this is different from questions that ask "I want a count for each distinct row in a table" which has been answered numerous times.注意:这与询问“我想要对表中每个不同的行进行计数”的问题不同,后者已被多次回答。 This is a filtered count, so the counting part of the query needs a more complex WHERE clause.这是一个过滤计数,因此查询的计数部分需要一个更复杂的 WHERE 子句。 Consider this dataset:考虑这个数据集:
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
I want to query this table and know the number of users over the age of 13 for each distinct customer_id.我想查询此表并了解每个不同的 customer_id 的 13 岁以上用户的数量。 So the result would be:所以结果是:
customer_id | over_13_count
-----------------------------
1 | 2
2 | 1
3 | 2
4 | 0
I've tried something like this but it just runs forever, so I think I'm doing it wrong:我试过这样的东西,但它会永远运行,所以我认为我做错了:
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
Just use conditional aggregation:只需使用条件聚合:
SELECT customer_id,
SUM(CASE WHEN age > 13 THEN 1 ELSE 0 END) asover_13_count
FROM mytable m1
GROUP BY customer_id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.