性别计数连接查询

时间:2012-04-13 12:18:49

标签: join count

我有三张桌子

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个事件。

任何建议都将不胜感激。

1 个答案:

答案 0 :(得分: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