GROUP BY每行获得几个聚合

时间:2018-02-28 15:30:33

标签: sql sql-server

我有一张桌子游戏,其中我有玩家_1,玩家2和胜者的ID

player_1   player_2   winner
1          2          1
1          2          1
1          3          3
2          3          2
2          1          2

我想查询最终结果类似于:

players     num_games_played   wins  
1|2         3                  2|1
1|3         1                  0|1
2|3         1                  1|0

基本上我需要按结果分组,以显示所玩游戏的列表和每位玩家的获胜次数。

我不确定我是应该坚持使用这种表还是制作一些关系表。

有关最佳方法的建议吗?

3 个答案:

答案 0 :(得分:1)

这是解决这个问题的一种方法。

if OBJECT_ID('tempdb..#Games') is not null
    drop table #Games

create table #Games
(   
    player1 int
    , player2 int
    , winner int
)

insert #Games values
(1, 2, 1)
, (1, 2, 1)
, (1, 3, 3)
, (2, 3, 2)
, (2, 1, 2)

select players = convert(varchar(5), player1) + '|' + convert(varchar(5), player2)
    , num_games_played = count(*)
    , convert(varchar(5), sum(case when winner = player1 then 1 else 0 end)) + '|' + convert(varchar(5), sum(case when winner = player2 then 1 else 0 end))
from
(
    select player1
        , player2
        , winner
    from #Games
    where player1 < player2

    union all

    select player2
        , player1
        , winner
    from #Games
    where player2 < player1
) x
group by convert(varchar(5), player1) + '|' + convert(varchar(5), player2)

答案 1 :(得分:0)

我会使用一些关系表,您可以轻松获得结果,如果您稍后进行一些允许来自两个以上玩家的更新,也会对您有所帮助。也许一张桌子上有游戏/比赛信息,另一张桌子上有游戏桌子,你有比赛的球员和比赛场地(胜利者)。

答案 2 :(得分:0)

这是另一个使用上述SQL查询

的类似想法的代码
with demo_solution as (
select 
p1=case when player1>player2 then player2 else player1 end,
p2=case when player1>player2 then player1 else player2 end,
winner
from Games
)
select 
players = cast(p1 as varchar)+'|'+cast(p2 as varchar),
num_games_played = count(1),
wins = cast(sum(case when winner=p1 then 1 else 0 end) as varchar)
     +'|'+
    cast(sum(case when winner=p2 then 1 else 0 end) as varchar)
from demo_solution
group by cast(p1 as varchar)+'|'+cast(p2 as varchar)