0

我在俱乐部和会议之间有一对多的结构

Clubs
Id    
1     
2
3
4

Meetings
Id    ClubId    MeeetingDate
1      1        2010-Mar-01
2      1        2010-Apr-01
3      2        2011-May-01
4      3        2011-Aug-01
5      3        2012-Sep-01
6      3        2012-Aug-01

我想获得所有俱乐部和大于getDate()

所以结果是

Club.Id    Count
1            0     (there are 0 meetings > getDate)
2            0     (there are 0 meetings > getDate)  
3            2     (there are 2 meetings > getDate)
4            0     (there are NO meetings)

我有一个解决方案,但它很丑!我的解决方案包含两个联合,一个存在,一个不存在。我确信有更好的方法,但我不得不承认这些天我写的 SQL 不多。

4

3 回答 3

3
SELECT c.id, 
       SUM(CASE WHEN m.meetingDate>GetDate() THEN 1 ELSE 0 END) AS Count
FROM clubs c
LEFT JOIN meetings m
    on c.id = m.clubid 
GROUP BY c.id

并以测试脚本作为证明(或者以防万一有人可以改进以上内容!):

;with clubs(id)
AS
(
    SELECT 1
    UNION SELECT 2
    UNION SELECT 3
    UNION SELECT 4
),
meetings(id, clubid, meetingdate)
AS
(
    SELECT 1,1,CAST('2010-03-01' AS DATE)
    UNION SELECT 2,1,'2010-04-01'
    UNION SELECT 3,2,'2011-05-01'
    UNION SELECT 4,3,'2011-08-01'
    UNION SELECT 5,3,'2012-09-01'
    UNION SELECT 6,3,'2012-08-01'
)
select c.id, SUM(CASE WHEN m.meetingDate>GetDate() THEN 1 ELSE 0 END) AS Count
from clubs c
left join meetings m
on c.id = m.clubid 
group by c.id
于 2012-04-30T13:17:09.273 回答
1

我的愚蠢疏忽。这里:

Select a.clubid, isnull(b.meetingcount,0) meetingcount    From clubs a
Left outer join (select clubid, count(*) meetingcount
                               From meetings 
                            Where meetingdate>getdate
 Group by clubid) b
On a.clubid=b.clubid
于 2012-04-30T13:20:43.103 回答
1
select c.id, count(m.id) as Count
from Clubs c
  left outer join Meetings m
    on c.id = m.clubid and 
       m.meetingdate > getdate() 
group by c.id
于 2012-04-30T13:23:01.963 回答