我在SQL server 2005 DB中有以下两个表
2-“UserInfomration”---> (ID(自动),姓名,性别(位))
1-“竞争对手”---> (Id(自动),UserID(来自UserInformation.ID的FK),状态(tinyint)
我想制作一个返回数据的存储过程,如下所示
状态 - 男性人数 - 女性人数
1 45 15
2个10 50
3 20 60
所以任何人都可以与我分享最佳解决方案 我的解决方案如下:
SELECT
Competitors.Status,
COUNT(Competitors.ID) AS MaleCount ,
(
SELECT Count(C.ID)
FROM Competitors as C , UserInfomration as UI
WHERE UI.UserID = C.UserID AND UI.UserGender = 0 AND C.Status = Competitors.Status
) as FemaleCount ,
(MaleCount + FemaleCount) as total
FROM
UserInfomration LEFT OUTER JOIN
Competitors ON UserInfomration.UserID = ISEFCompetitors.UserID
GROUP BY Competitors.Status, UserInfomration.UserGender
HAVING (UserInfomration.UserGender = 1)
ORDER BY Competitors.Status
提前感谢您的合作
答案 0 :(得分:1)
您可以尝试这样的事情
SELECT c.Status,
SUM(CASE WHEN u.Gender = 0 THEN 1 ELSE 0 END) Male, --assuming 0 is male
SUM(CASE WHEN u.Gender = 1 THEN 1 ELSE 0 END) Female --assuming 1 is female
FROm Competitors c INNER JOIN
UserInfomration u ON c.UserID = u.ID
GROUP BY c.Status