以下是包含数据的锦标赛表格结构。
|-------|-----------| | Team | Result | |-------|-----------| | A | Win | |-------|-----------| | A | Loss | |-------|-----------| | A | Draw | |-------|-----------| | B | Win | |-------|-----------| | B | Win | |-------|-----------| | C | Loss | |-------|-----------| | C | Loss | |-------|-----------| | A | Draw | |-------|-----------| | C | Win | |-------|-----------|
以下是必填结果
|-------|-----------|--------|--------|---------| | Team | Win | Loss | Draw | Total | |-------|-----------|--------|--------|---------| | A | 1 | 1 | 2 | 4 | |-------|-----------|--------|--------|---------| | B | 2 | 0 | 0 | 2 | |-------|-----------|--------|--------|---------| | C | 1 | 0 | 2 | 3 | |-------|-----------|--------|--------|---------|
我试图获得此结果,但它也包含重复记录。
select team,count(case when result='Won' then 1 else null end) over(PARTITION BY result,team ) as "Win",
count(case when result='Loss' then 1 else null end) over(PARTITION BY result,team) as "Loss",
count(case when result='Draw' then 1 else null end) over(PARTITION BY result,team) as "Draw"
from Tournament;
with t
as
(select team,count(case when result='Won' then 1 else null end) over(PARTITION BY result,team ) as "Win",count(case when result='Loss' then 1 else null end) over(PARTITION BY result,team) as "Loss",count(case when result='Draw' then 1 else null end) over(PARTITION BY result,team) as "Draw"
from Tournament)
select distinct t.team, count(t."Win") as a,count(t."Loss") b,t."Draw" from t group by t.team,t."Win",t."Loss",t."Draw" ;
答案 0 :(得分:2)
您为什么使用vehicle
?我通常使用此语法进行累计计数,如果您只是想要计数,那么请使用count() over()
和COUNT()
CASE EXPRESSION
的常规GROUP BY
:
select team,count(case when result='Won' then 1 end) as "Win",
count(case when result='Loss' then 1 end) as "Loss",
count(case when result='Draw' then 1 end) as "Draw",
count(*) as total
from Tournament
GROUP BY team
此外,不需要ELSE NULL
,因为它是CASE EXPRESSION
的默认值。
答案 1 :(得分:0)
不使用案例或分区的替代方法
SELECT * FROM (SELECT trim(upper(result))RESULT1,TEAMNAME FROM Tournament) PIVOT(计数(1)AS RESULT_COUNT FOR(RESULT1)IN(&#39; WIN&#39; AS WIN,&#39; LOSS&#39; AS LOSS,&#39; DRAW&#39; as DRAW)); < / p>