I have a table "Events" and a table “Slots” where Slots.SlotID = Events.MainSlot OR Events.ExtraSlot.
I need to sum the number of “Attendees” per time slot (as MainSlot and as ExtraSlot - ExtraSlot is optional)
Table "Events"
ID------Name----------MainSlot-------ExtraSlot-------Attendees
1-------Event1--------1 -------------n/a-------------20
2-------Event2--------1 -------------n/a-------------20
3-------Event3--------2 -------------n/a-------------40
4-------Event4--------2 -------------3---------------20
5-------Event5--------3 -------------4---------------40
6-------Event6--------3 -------------4---------------20
7-------Event7--------3 -------------4---------------10
Table "Slots"
SlotID--- Slot
1-------- 9.00-9.30
2-------- 9.30-10
3-------- 10.30-10.30
4-------- 10.30-11
If I query the database separately as follows:
SELECT s.Slot, s.SlotID, ISNULL(SUM(e. Attendees), 0) AS Attendees1
FROM Slots AS s
LEFT OUTER JOIN Events AS e ON e.MainSlot = s.SlotID
GROUP BY s.Slot, s.SlotID
...or:
SELECT s.Slot, s.SlotID, ISNULL(SUM(x.Attendees), 0) AS Attendees2
FROM Slots AS s
LEFT OUTER JOIN Events AS x ON x.ExtraSlot = s.SlotID
GROUP BY s.Slot, s.SlotID
I get the following, respectively:
SlotID ------ Attendees1
1------------- 40
2------------- 60
3------------- 70
4------------- 0
SlotID ------- Attendees2
1------------- 0
2------------- 0
3------------- 20 *correct
4------------- 70
Both results are correct.
However if I put the two queries together something is wrong as shows the table below
SELECT s.Slot, s.SlotID, ISNULL(SUM(e.Attendees), 0) AS Attendees1,
ISNULL(SUM(x. Attendees), 0) AS Attendees2
FROM Slots AS s LEFT OUTER JOIN
Events AS e ON e.MainSlot = s.SlotID LEFT OUTER JOIN
Events AS x ON x.ExtraSlot = s.SlotID
GROUP BY s.Slot, s.SlotID
SlotID------------- Attendees1---------- Attendees2
1-------------------40-------------------0
2-------------------60-------------------0
3-------------------70------------------60 *wrong
4-------------------0-------------------70
What am I doing wrong? Thanks for your help!