Count + Distinct SQL Query

时间:2014-03-12 16:19:32

标签: sql postgresql

我有一个类似

的研究表
researcher    award

 person1      award1
 person1      award2
 person2      award3

我想得到的是根据研究人员来计算奖励,但研究人员不应该这样做 重复。所以在这个例子中。结果应该是

 2

Coz award1和award2是同一个人+ award3,是另一个人。

我已经尝试了

SELECT count(award) from research where researcher=(select distinct(researcher) from researcher)

但它说

ERROR:  more than one row returned by a subquery used as an expression

那么任何替代解决方案或变化?

4 个答案:

答案 0 :(得分:2)

这将为您提供研究人员和计数

select researcher, count(*) as c
from table
group by researcher

也许你只想要获奖者?

select researcher, count(*) as c
from table
where award is not null
group by researcher

答案 1 :(得分:0)

你可以做一个小组并统计不同的奖项。

SELECT count(distinct award) from research group by researcher

答案 2 :(得分:0)

您只需使用GROUP BY

SELECT    COUNT( DISTINCT Award ) AS awardCount 

FROM      Research 

GROUP BY  Researcher

答案 3 :(得分:0)

select count(*) from (select researcher, count(*) 
from MyTable
group by researcher) as tempTable;