以一对多关系返回父行和子聚合的最有效方法

时间:2012-08-31 16:51:45

标签: sql sql-server-2008

假设我有两个表与一对多的关系。我想创建一个视图/查询,显示父行的所有列和子行的总计。这是我经常遇到的情况,我不禁感到我错过了一个更好,更明显的解决方案。我使用的是针对子表的多个连接,例如:

SELECT vt.*, COALESCE(count(mvAyes.*), 0) as Ayes, COALESCE(count(mvNoes.*), 0) as Noes  FROM VoteTable vt 
LEFT JOIN MemberVote mvAyes on mvAyes.VoteId = vt.Id AND mvAyes.Vote = 'Aye'
LEFT JOIN MemberVote mvNoes on mvNoes.VoteId = vt.Id AND mvNoes.Vote = 'No'
GROUP BY vt.Col1, vt.Col2 ... (all columns in Vote table)

另一个解决方案是使用相关的子查询,据我所知,这是非常低效的,尽管我认为上面的多连接解决方​​案也是非常低效的。

那么,有没有更好的解决方案,我不知道?谢谢!

1 个答案:

答案 0 :(得分:2)

是的,有一个更简单的解决方案:

SELECT vt.*,
       sum(case when mv.Vote = 'Aye' then 1 else 0 end) as Ayes,
       sum(case when mv.Vote = 'No' then 1 else 0 end) as Nos
FROM VoteTable vt left outer join
     MemberVote mv
     on mv.VoteId = vt.Id 
GROUP BY vt.Col1, vt.Col2 ... (all columns in Vote table)

您可以通过在子查询中执行分组来进一步简化:

select vt.*, mv.ayes, mv.noes
from vt left outer join
     (select VoteId, sum(case when mv.Vote = 'Aye' then 1 else 0 end) as Ayes,
             sum(case when mv.Vote = 'No' then 1 else 0 end) as Nos
      from MemberVote mv
      group by VoteId
     ) mv
     on vt.id = mv.VoteId