如何使用具有多个表的Count()返回零

时间:2009-10-19 19:35:47

标签: sql sql-server tsql join count

我有三个表(SQL Server)

月 - month_id,月份名称,....

奖励 - award_id,奖励名称,....

提名 - fk_award_idfk_month_id,姓名,地址,......

我需要计算每月奖励的不同类型奖项的数量,而在没有奖励的情况下返回0奖励

表示例如 结果应该看起来像

April-09     Gold         10   
April-09     Silver        2  
April-09     Bronze        0    
May-09       Gold          2   
May-09       Silver        1   
May-09       Bronze        0  

这可能吗?

3 个答案:

答案 0 :(得分:2)

要测试的一些数据:

DECLARE @months TABLE
( month_id INT IDENTITY,
month_name VARCHAR(50)
)

INSERT INTO @months(month_name) VALUES ('April-09')
INSERT INTO @months(month_name) VALUES ('May-09')

DECLARE @awards TABLE
( award_id INT IDENTITY,
award_name VARCHAR(50)
)

INSERT INTO @awards(award_name) VALUES ('Bronze')
INSERT INTO @awards(award_name) VALUES ('Silver')
INSERT INTO @awards(award_name) VALUES ('Gold')

DECLARE @nominations TABLE
( fk_month_id INT,
fk_award_id INT,
other_field VARCHAR(10)
)

INSERT INTO @nominations(fk_month_id,fk_award_id,other_field) VALUES (1,1,'1')
INSERT INTO @nominations(fk_month_id,fk_award_id,other_field) VALUES (1,1,'2')
INSERT INTO @nominations(fk_month_id,fk_award_id,other_field) VALUES (2,2,'3')
INSERT INTO @nominations(fk_month_id,fk_award_id,other_field) VALUES (2,1,'4')
INSERT INTO @nominations(fk_month_id,fk_award_id,other_field) VALUES (3,1,'5')
INSERT INTO @nominations(fk_month_id,fk_award_id,other_field) VALUES (3,2,'6')
INSERT INTO @nominations(fk_month_id,fk_award_id,other_field) VALUES (3,2,'7')

和查询

SELECT month_name, award_name, ISNULL(cnt,0) 
FROM @months
CROSS JOIN @awards
LEFT JOIN ( 
    SELECT fk_month_id,fk_award_id, COUNT(*) AS cnt
    FROM @nominations 
    GROUP BY fk_month_id,fk_award_id
) fk ON fk_month_id = month_id AND fk_award_id = award_id

结果是:

April-09  Bronze  2
April-09  Silver  0
April-09  Gold    0
May-09    Bronze  1
May-09    Silver  1
May-09    Gold    0

答案 1 :(得分:0)

group by month_id, award_id plus out join会做到这一点

答案 2 :(得分:0)

这样的东西就是你所需要的。未经测试,但原则是:

SELECT m.Monthname, a.Awardname, COUNT(*)
    FROM Month m
       LEFT JOIN Nomination n ON n.fK_Month_ID = m.MonthID
       LEFT JOIN Award a ON n.FK_Award_ID = a.AwardID
    GROUP BY m.Monthname, a.Awardname

关键是GROUP BY子句。