使用GROUP BY构建SQL

时间:2015-12-18 20:04:47

标签: sql postgresql

我需要创建一个SQL,它会为我提供一个类别的粉丝总数。

select count(fo.id) 
from fans_fanofvote as fov, fans_fanof as fo
where fov.fanof_id = fo.id
GROUP BY fo.fanofcategory_id

但问题是粉丝可以为一个类别投票超过一次,因此我的查询返回MMA的2个粉丝,但它应该是1,因为FAN(id:1)已经为该类别投了两次。

FanOf
ID FANOFCATEGORY  NAME  
== ============== =====
1   1             Ronda Rousey
2   1             GSP
3   2             Carey Price
4   2             Sidney Crosby

FanOfCategory

ID  NAME
== ======
1   MMA
2   Hockey
3   Football

FanOfVote

ID  FAN FANOF
== ==== =====
1   1   1
2   1   2
3   2   3
4   1   4
5   1   3 

1 个答案:

答案 0 :(得分:2)

获取每个类别以及投票赞成的不同粉丝的数量:

select foc.name, count(distinct fov.fan) 
from fans_fanofvote as fov
join fans_fanof as fo
    on fov.fan = fo.id
join fanofcategory foc
    on fo.fanofcategory = foc.id
GROUP BY foc.name

获取特定类别的不同粉丝数量:

declare @CategoryID int = 1 //This should be a parameter, but just putting it here so you can test

select count(distinct fan)
from fanofvote
where fanof = @CategoryID