SQL计数唯一出现的性别

时间:2015-03-12 13:14:13

标签: sql sql-server sql-server-2008

我有3张表(人口统计),(LINK)和(入场)

SELECT SUM(CASE dmg.dmg_Sex WHEN 'Male' THEN 1 END) AS male,
       SUM(CASE dmg.dmg_Sex WHEN 'Female' THEN 1 END) AS female,
FROM Demographic dmg
JOIN LINK lnk ON lnk.lnk_dmgID = dmg.dmg_ID
JOIN Admission adm ON adm.adm_ID = lnk.lnk_admID
WHERE adm.adm_ReferralDate >= '01/01/2011' AND adm.adm_ReferralDate <= '31/03/2011'

我试图在日期范围内总结性别。 这不行,我是在正确的轨道上吗?

只是在没有SUMCASE的情况下执行普通查询100%。

enter image description here

2 个答案:

答案 0 :(得分:2)

SELECT SUM(CASE dmg.dmg_Sex WHEN 'Male' THEN 1 END) AS male,
       SUM(CASE dmg.dmg_Sex WHEN 'Female' THEN 1 END) AS female
FROM Demographic dmg
JOIN LINK lnk ON lnk.lnk_dmgID = dmg.dmg_ID
JOIN Admission adm ON adm.adm_ID = lnk.lnk_admID
WHERE adm.adm_ReferralDate >= '01/01/2011' AND adm.adm_ReferralDate <= '31/03/2011'

答案 1 :(得分:1)

使用GROUP BY

SELECT dmg.dmg_Sex, COUNT (dmg.dmg_Sex)
FROM Demographic dmg
JOIN LINK lnk ON lnk.lnk_dmgID = dmg.dmg_ID
JOIN Admission adm ON adm.adm_ID = lnk.lnk_admID
WHERE adm.adm_ReferralDate >= '01/01/2011' 
AND adm.adm_ReferralDate <= '31/03/2011'
GROUP BY dmg.dmg_Sex