在SQL中使用count with condition

时间:2017-08-14 13:39:46

标签: sql

编写一个查询以显示球队名称和锦标赛中球队的胜利数。如果任何一支球队没有赢得任何一场比赛,请将win_count显示为0.给胜利数字命名为“win_count”#39;。显示基于团队名称按升序排序的记录。

我尝试了此查询,但它无效

select 
    t.name, count(case when o.status='WIN' then true else '0') as win_count   
from 
    team t 
inner join 
    outcome o on t.id = o.winner_team_id
group by 
    t.name
order by 
    t.name asc

示例数据:

TEAM

    ID  NAME    
    -----------------
    1   BENGAL  
    2   BENGALURU   
    3   DELHI   
    4   JAIPUR
    5   PATNA   
    6   PUNE    
    7   PUNJAB  
    8   KOLKATA

观察

    ID  STATUS  WINNER_TEAM_ID  
    ---------------------------
    1   WIN     2
    2   WIN     4
    3   WIN     5
    4   WIN     7
    5   CANCELLED   NULL
    6   WIN     4
    7   WIN     8
    8   WIN     7   
    9   WIN     8
    10  WIN     7
    11  WIN     2
    12  WIN     1   
    13  WIN     4
    14  WIN     2
    15  WIN     5
    16  WIN     5   
    17  WIN     8   
    18  WIN     7   
    19  WIN     4   
    20  WIN     3
    21  WIN     4   
    22  WIN     2   

1 个答案:

答案 0 :(得分:0)

最容易通过分组来完成。

SELECT t.Name, COUNT(o.ID) AS WIN_COUNT
FROM Team t
LEFT JOIN Outcome o ON o.Winner_Team_ID = t.ID
GROUP BY t.ID
ORDER BY t.Name;