首先抱歉这个问题没有描述我的问题,我不知道如何将其作为问题来说明。
我想算一下,每个分支机构都有多少名担任职位主管的女性和男性。
所以这是SQL:
CREATE VIEW Women (BranchID,AnzahlF,position ) AS
SELECT Branch.BranchID, COUNT(*) As AnzahlF,Staff.position
FROM Staff full outer JOIN
Branch ON Branch.BranchID = Staff.BranchFK
WHERE gender LIKE 'F' AND position LIKE 'Supervisor'
GROUP BY Branch.BranchID,Staff.position
CREATE VIEW Men (BranchID,AnzahlM,position ) AS
SELECT Branch.BranchID,COUNT(*) As AnzahlM ,Staff.position
FROM Staff Full outer JOIN
Branch ON Branch.BranchID = Staff.BranchFK
WHERE gender LIKE 'M' AND position LIKE 'Supervisor'
GROUP BY Branch.BranchID,Staff.position
Select ISNULL(Women.BranchID, Men.BranchID) AS BranchID,
Case When (Women.AnzahlF is Null) THEN 0
ELSE Women.AnzahlF END As ANzahlFSuperv,
Case When (Men.AnzahlM is Null) THEN 0
ELSE Men.AnzahlM END As ANzahlMSuperv
from Women Full outer join Men On Women.BranchID = Men.BranchID
Group by Women.BranchID, Men.BranchID,Women.ANzahlF,Men.AnzahlM Order by BranchID
这是输出:
BranchID,ANzahlFSuperv,ANzahlMSuperv
B001,2,0
B003,1,1
B004,1,1
B005,1,0
B006,1,0
B007,0,2
B008,1,1
B009,0,1
B010,0,1
B011,1,0
B012,0,1
B013,1,0
B014,1,0
=>缺少B002,0,0
但我没有得到ID为'B002'的分支,它有ANzahlFSuperv = 0和ANzahlMSuperv = 0.所以它没有超级监督者。那么如何得到这个结果?
解决方案必须在视图中,以便如何获取此BranchID。
我尝试了一切但没有价值。
希望你们能解雇我!
谢谢!
答案 0 :(得分:1)
为什么要为此使用视图?只需left join
和group by
:
SELECT b.BranchID, COUNT(*) As AnzahlM,
SUM(CASE WHEN s.gender = 'F' THEN 1 ELSE 0 END) as females,
SUM(CASE WHEN s.gender = 'M' THEN 1 ELSE 0 END) as males
FROM Branch b LEFT JOIN
Staff s
ON b.BranchID = s.BranchFK AND s.position = 'Supervisor'
GROUP BY b.BranchID;