我们如何合并两个查询的结果具有分组依据和两个条件

时间:2015-06-13 15:28:07

标签: sql sql-server group-by

我有这两个表:(游戏)

games table

和(轮次)表:

rounds table

我想得到游戏ID,有圆计数,以及玩家1获胜的轮数。我创建了两个这样的SQL查询:

queries and results

但我想在一张桌子上得到所有结果。如何将结果组合成如下: enter image description here

2 个答案:

答案 0 :(得分:2)

您可以使用条件聚合

SYSENTER

Demo here

答案 1 :(得分:2)

您可以将2个单独查询的结果与派生表结合使用:

select
  A.gameId, 
  A.roundsCount,
  B.p1WinsCount
from
  (
     select g.Id as gameId, count(r.Id) as roundsCount
     from game g, rounds r
     where g.Id = r.game_id
     group by g.Id
   ) A,
   (
     select g.Id as gameId, count(r.Id) as p1WinsCount
     from game g, rounds r
     where r.winner = g.player1_id
     group by g.Id
    ) B
where
  A.gameId = B.gameId

但在这种情况下,你也可以做得更简单:

 select 
   g.Id as gameId, 
   count(r.Id) as roundsCount, 
   sum(case when r.winner = g.player1_id then 1 else 0 end) as p1WinsCount
 from 
   game g
   join rounds r on g.Id = r.game_id
 group by 
   g.Id