如何使用group by生成不符合计数条件的记录

时间:2017-02-22 21:12:40

标签: sql sql-server tsql

我正在尝试生成池匹配的结果。我正在计算一名球员在比赛中赢得的帧数,但是对于那些没有赢得一帧的人来说,我很难产生结果。

我已经读过,当使用一个计数和一组返回0的记录被删除但不确定我可以使用的任何其他方法。

请您在下面建议我如何改进我的查询,谢谢:)

select 
    t1.Match_ID,
    t1.Home_Player_ID,
    Frames_Won,
    coalesce(Frames_Lost,0) as Frames_Lost
from 
    (
    select 
        Match_ID,
        Home_Player_ID, 
        count(*) as Frames_Won 
    from 
        Match 
    where 
        Home_Player_Win = 1 
    and 
        Match_ID = '56D4FF05-5F33-43FC-A566-2251E790C57F' 
    group by 
        Match_ID,
        Home_Player_ID
    ) t1
left join
    (
    select 
        Match_ID,
        Home_Player_ID, 
        count(*) as Frames_Lost 
    from 
        Match 
    where 
        Home_Player_Win = 0 
    and 
        Match_ID = '56D4FF05-5F33-43FC-A566-2251E790C57F' 
    group by 
        Match_ID,
        Home_Player_ID
    ) t2
on t1.Home_Player_ID = t2.Home_Player_ID 

1 个答案:

答案 0 :(得分:2)

我认为您缺少用户未赢得任何游戏的记录,因为home_player_win = 1的第一个子查询限制。

这个查询有什么理由不起作用吗?

SELECT
Match_ID,
Home_Player_ID,
SUM(home_player_win)
FROM match
WHERE Match_ID = '56D4FF05-5F33-43FC-A566-2251E790C57F' 
GROUP BY Match_ID, Home_Player_ID;