0

这是一个示例架构:

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

我想要的是对具有相同university_iduniversity_id本身的记录数量进行计数,并且它不能包含 的重复项type_id,因此对于上面给出的相同数据,结果将如下所示:

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

现在我正在尝试以下方法,但它显然会给我一个COUNT(u01)of3而不是2

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

是否可以做我想做的事,如果可以,怎么做?

4

2 回答 2

3

You should count by type_id uniquely not by university_id

SELECT university_id, COUNT(DISTINCT type_id) TotalCount
FROM   tableName
GROUP  BY university_id
于 2013-05-02T14:31:01.500 回答
1

你需要一个count(distinct)type_id列上:

select university_id, count(distinct type_id)
from table
group by university_id
于 2013-05-02T14:32:56.957 回答