IsoFunCode
IsoFunCode

Reputation: 57

SQL Outer Join views

first of all sorry the question does not describes my problem and I don't know how to tell it as question.

I want to count how many women and men with position supervisor works in every branch.

So this is the 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

This is the output: 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
=> Missing B002, 0,0

But I do not get the Branch with ID 'B002' it has ANzahlFSuperv = 0 and ANzahlMSuperv = 0. So it has no supersivisor. So how to get this result?

The solution must be in the views so how to get this BranchID.

I tried everything but worthless.

Hope you guys can hep me!

Thanks!

Upvotes: 1

Views: 27

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269753

Why would you use views for this? Just a left join and 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;

Upvotes: 1

Related Questions