简体   繁体   English

选择COUNT个值,按同一列分组,在另一列上不同

[英]Selecting a COUNT of values, grouped by that same column, distinct on another

Here's a sample schema: 这是一个示例架构:

| type_id | university_id |
---------------------------
|    1    |      u01      |
|    2    |      u01      |
|    2    |      u01      |
|    3    |      u02      |
|    4    |      u02      |

And what I want is a count of the amount of records that have the same university_id , the university_id itself, and it must not include duplicates of type_id , so the result would look like this for the same data given above: 我想要的是对具有相同university_iduniversity_id本身的记录数量进行计数,并且它一定不能包含type_id重复项,因此对于上面给出的相同数据,结果看起来像这样:

| university_id | COUNT(university_id) |
----------------------------------------
|      u01      |          2           |
|      u02      |          2           |

Right now I'm trying the following, but it will clearly give me a COUNT(u01) of 3 instead of 2 现在,我正在尝试以下操作,但是它显然会给我COUNT(u01) 3而不是2

SELECT university_id, COUNT(university_id) FROM table GROUP BY university_id

Is it possible to do what I want, and if so how? 是否可以做我想做的事情,如果可以,怎么做?

You should count by type_id uniquely not by university_id 您应该按type_id唯一地计数,而不type_id university_id计数

SELECT university_id, COUNT(DISTINCT type_id) TotalCount
FROM   tableName
GROUP  BY university_id

You need a count(distinct) on the type_id column: 您需要在type_id列上添加一个count(distinct)

select university_id, count(distinct type_id)
from table
group by university_id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM