简体   繁体   English

PostgreSQL 当被另一列分组时从一列计数 DISTINCT

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

相关问题 SQL如何在另一列不同时计算一列 - SQL How to count one column when another column is distinct MySQL-计算基于另一列的一列中的不同值 - MySQL - count distinct values from one column based on another column PostgreSQL 不同的行与一列中的不同值的计数相连 - PostgreSQL distinct rows joined with a count of distinct values in one column 从另一列获取不同的行数 - Get a distinct row count from another column mysql从一列返回不同的值,按计数按另一列分组 - mysql return distinct values from one column, group by another column with count 当另一列相同时计算按列分组的行 - Count rows grouped by a column when another column is the same **SQLAlchemy**:获取另一列不同的一列的计数 - **SQLAlchemy**:Get a count of one column where another column is distinct 使用另一列中的多个值计算一列中的不同记录 - Count distinct records in one column with multiple values in another column PostgreSQL - 从日期列获取不同年份的计数 - PostgreSQL - get count of distinct years from date column SQL查询可返回第一列的不同计数,同时允许第二列的全部求和,并按第三列分组 - SQL Query to return a distinct count of one column while allowing a full summation of a second column, grouped by a third
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM