2012-04-13 43 views
0

我有三個表性別計聯接查詢

Member - MemberID, gender, etc 
Venue - VenueID, City, VenueName, etc 
Event - EventID, EventDate, etc 

試圖顯示一個查詢,顯示男性和女性對所在的城市是格拉斯哥每個事件和2012年1月

的時間期間的計

到目前爲止我的結果是。

SELECT Venue.VenueName, Venue.City, Event.Eventdate, (select count(gender) from member where gender = 'm') AS MaleTotal, (select count(gender) from member where gender = 'f') AS FemaleTotal 
FROM Venue INNER JOIN Event ON Venue.VenueID = Event.FKvenueID 
WHERE Venue.City='Glagow' and Month(eventdate)=1 and year(partydate) = 2011; 

這產生表示

VenueName-ABC Venue, XYZVenue; 

City- Glasgow, Glasgow; 

Partydate- 04/01/2012, 05/01/2012 

MaleTotal-4,4 

FemaleTotal-3,3 

哪個是錯誤的原因有總共只在成員表7個的條目,並且每個僅參加1個事件的表。

任何建議將不勝感激。

+0

看來你缺少活動和成員之間的聯繫。你需要考慮你的'男性'''女性'結果子查詢。 '(從成員where性別='m'和memberId中選擇計數(性別)(從member_events where member_events .eventID = Event.EventId中選擇memberId)'其中'member_events'是保存成員和事件之間關係的表他們在英國註冊。 – Dutchie432 2012-04-13 12:31:43

回答

0

假設有一個許多成員和事件之間的多對多關係,你可以嘗試這樣的事情

SELECT Venue.VenueName, 
     Venue.City, 
     Event.Eventdate, 
     SUM (CASE gender WHEN 'm' THEN 1 ELSE 0 END) AS MaleTotal, 
     SUM (CASE gender WHEN 'f' THEN 1 ELSE 0 END) AS FemaleTotal 
FROM Venue INNER JOIN 
    Event ON Venue.VenueID = Event.FKvenueID INNER JOIN 
    Event_Member ON Event_Member.EventID = Event.EventID INNER JOIN 
    Member ON Member.MemberID = Event_Member.MemberID 
WHERE Venue.City='Glagow' 
    and Month(eventdate)=1 
    and year(partydate) = 2011 
GROUP BY Venue.VenueName, 
     Venue.City, 
     Event.Eventdate