根据where子句和左连接获取所有父母和子女数量

时间:2012-04-30 13:06:08

标签: sql-server tsql

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

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。

3 个答案:

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

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

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