当按另一列分组时,PostgreSQL 计数与一列不同

发布于 2025-01-10 22:42:09 字数 674 浏览 0 评论 0原文

我有一个如下所示的表(简化):

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

陈独秀 2025-01-17 22:42:09

刚刚发现有一个 COUNT(DISTINCT( 选项,它不需要将不同的值放置在分组子句中。

SELECT COUNT(DISTINCT userid) FROM data GROUP BY state

有技巧吗

Just found out that there's a COUNT(DISTINCT( option which doesn't require that distinct value to be placed in the grouping clause.

SELECT COUNT(DISTINCT userid) FROM data GROUP BY state

Does the trick

木槿暧夏七纪年 2025-01-17 22:42:09

您可以尝试以下格式:

SELECT COUNT(DISTINCT userid) FROM data GROUP BY state

You can try out the below format:

SELECT COUNT(DISTINCT userid) FROM data GROUP BY state
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文