简体   繁体   English

SQL:如何获取表中每个不同行的筛选计数?

[英]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.

相关问题 在 BigQuery SQL 中获取不同的计数并重复每行 - get a distinct count and repeating per row in BigQuery SQL SQL 从两个表中计数(不同) - SQL count(distinct) from both the table 根据每个行值计算表中的行数 - Count rows in a table based on each row value 如何在速视中进行不同的计数和 if else 语句? - How to do distinct count and if else statement in quicksight? 如何使用 bigquery 计算每列的项目频率? - How do I count the frequency of items for each column with bigquery? 如何从 SQL 的另一行中取最小值? - How do I take the minimum value from another row in SQL? 您如何按看到的第一个月计算不同的客户和组? - How do you count Distinct Customers and group by first month seen? 如何将一个表中的多行插入到另一个表的单行的结构列中? - How do I insert multiple rows from one table into a struct column of a single row of another table? 如何在 cloudwatch 中查找不同的计数或显示不同的日志消息 - How to find distinct count or display distinct log message in cloudwatch 如何(空间)将许多表连接到另一个 BigQuery 表的每一行? - How to (spatial) JOIN many tables to each row of another BigQuery table?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM