[英]PostgreSQL Count DISTINCT from one column when grouped by another
I have a single table that looks like the following (dumbed down):我有一个表,如下所示(简化):
userid | action | userstate
-----------------------------------------------------
1 | click | Maryland
2 | press | Delaware
3 | jog | New York
3 | leap | New York
What I'm trying to query is "number of users doing ANY action, per state"我要查询的是“每个州执行任何操作的用户数量”
So the result would be:所以结果是:
state | users_acting
---------------------
Maryland | 1
Delaware | 1
New York | 1
Note that individual users will only be part in one state.请注意,个人用户只会参与一个 state。
I can't get the mix of distinct users correct with grouping by state. I can't我无法通过按 state 分组来正确混合不同用户。我不能
SELECT DISTINCT (userid), COUNT(userid) FROM data GROUP BY state
because the distinct column needs to be in the group by, which I don't want to actually do, not to mention problems w/ the select clause.因为不同的列需要在分组依据中,我实际上不想这样做,更不用说 select 子句的问题了。
Thanks for any thoughts.感谢您的任何想法。
Just found out that there's a COUNT(DISTINCT( option which doesn't require that distinct value to be placed in the grouping clause.刚发现有一个 COUNT(DISTINCT( 选项不需要将不同的值放在分组子句中。
SELECT COUNT(DISTINCT userid) FROM data GROUP BY state
Does the trick做的伎俩
You can try out the below format你可以试试下面的格式
SELECT COUNT(DISTINCT userid) FROM data GROUP BY state SELECT COUNT(DISTINCT userid) FROM data GROUP BY state
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.