当按另一列分组时,PostgreSQL 计数与一列不同
我有一个如下所示的表(简化):
userid | action | userstate
-----------------------------------------------------
1 | click | Maryland
2 | press | Delaware
3 | jog | New York
3 | leap | New York
我试图查询的是“每个州执行任何操作的用户数量”
因此结果将是:
state | users_acting
---------------------
Maryland | 1
Delaware | 1
New York | 1
请注意,单个用户只会参与一个状态。
我无法通过按州分组正确地混合不同的用户。我不能,
SELECT DISTINCT (userid), COUNT(userid) FROM data GROUP BY state
因为不同的列需要位于 group by 中,而我实际上不想这样做,更不用说 select 子句的问题了。
感谢您的任何想法。
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.
I can't get the mix of distinct users correct with grouping by state. I can't
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.
Thanks for any thoughts.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
刚刚发现有一个 COUNT(DISTINCT( 选项,它不需要将不同的值放置在分组子句中。
有技巧吗
Just found out that there's a COUNT(DISTINCT( option which doesn't require that distinct value to be placed in the grouping clause.
Does the trick
您可以尝试以下格式:
You can try out the below format: