返回SQL中的记录数

时间:2016-10-08 13:09:26

标签: sql oracle10g

我有一张桌子

​SQL> select * from CRICKET_DETAILS;
TEAM1                TEAM2                WINNER
-------------------- -------------------- --------------------
INDIA                PAKISTAN             INDIA
INDIA                SRILANKA             INDIA
SRILANKA             INDIA                INDIA
PAKISTAN             SRILANKA             SRILANKA
PAKISTAN             ENGLAND              PAKISTAN
SRILANKA             ENGLAND              SRILANKA

6 rows selected.
​

我想要这样的输出:

TEAM          PLAYED      WON      LOST
ENGLAND          2          0         2          
INDIA            3          3         0
PAKISTAN         3          1         2
​SRILANKA         4          2         2

2 个答案:

答案 0 :(得分:1)

我会选择group byunion all

select team, count(*), sum(won), sum(lost)
from ((select team1 as team,
              (case when winner = team1 then 1 else 0 end) as won,
              (case when winner = team1 then 0 else 1 end) as lost
       from cricket_details cd
      ) union all
      (select team2,
              (case when winner = team2 then 1 else 0 end) as won,
              (case when winner = team2 then 0 else 1 end) as lost
       from cricket_details cd
      )
     ) tt
group by team;

答案 1 :(得分:0)

select team, count(*) as played, 
       count(case when result = 'W' then 1 end) as won,
       count(case when result = 'L' then 1 end) as lost
from ( select team3 as team, 'W' as result from cricket_details union all
       select case team3 when team1 then team2 else team1 end, 'L' from cricket_details)
group by team;