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 个活动。

任何建议将不胜感激。

4

1 回答 1

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
于 2012-04-13T12:37:10.510 回答