我有这两个表:(游戏)
和(轮次)表:
我想得到游戏ID,有圆计数,以及玩家1获胜的轮数。我创建了两个这样的SQL查询:
但我想在一张桌子上得到所有结果。如何将结果组合成如下:
答案 0 :(得分:2)
答案 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