2

如果我的表看起来像这样,我如何在 mysql 中获得所需的结果。

结果|年份

1 |2011

2 |2011

1 |2011

0 |2011

1 |2012

2 |2012

1 = 赢,2 = 输,0 = 平局

每年都可以有多个这样的值。不知道如何获得如下所示的预期结果。

year  won  lost  draw  totalPlayed
2011  2     1     1       3
2012  1     1     0       2

我尝试了以下查询,但没有得到想要的结果

select year,
league_types.league_name, 
sum(if(result = 1,1,0)) as won,
sum(if(result = 0,1,0)) as draw,
sum(if(result = 4,1,0)) as noResult,
sum(if(result = 2,1,0)) as lost, 
sum(if(result = 3,1,0)) as tied, 
sum(if(result > 0 and result < 4,1,0)) as played 
from match_score_card 
inner join fixtures on match_score_card.match_id = fixtures.match_id
inner join league_types on fixtures.league_id = league_types.league_id
where 
team_id = 1 group by year order by year desc
4

2 回答 2

1

这是演示以下查询的SQL Fiddle

SELECT m.year,
  SUM(CASE WHEN m.result = 1 THEN 1 ELSE 0 END) AS 'Won',
  SUM(CASE WHEN m.result = 2 THEN 1 ELSE 0 END) AS 'Lost',
  SUM(CASE WHEN m.result = 0 THEN 1 ELSE 0 END) AS 'Draw',
  COUNT(*) AS 'TotalPlayed'
FROM MyTable AS m
GROUP BY m.year
于 2013-11-09T21:05:35.703 回答
0

我不熟悉 mySQL 中的 IF 函数,但是这个标准 SQL 应该可以工作:

select year
     , league_types.league_name 
     , sum(CASE WHEN result = 1 THEN 1 ELSE 0 END) as won
     , sum(CASE WHEN result = 2 THEN 1 ELSE 0 END) as lost
     , sum(CASE WHEN result = 3 THEN 1 ELSE 0 END) as draw
     , sum(CASE WHEN result = 4 THEN 1 ELSE 0 END) as noResult
     , sum(CASE WHEN result = 1
                  or result = 2 THEN 1 ELSE 0 END) as played
from match_score_card 
inner join fixtures 
on match_score_card.match_id = fixtures.match_id
inner join league_types 
on fixtures.league_id = league_types.league_id
where team_id = 1 
group by year, league_types.league_name
order by year desc, league_types.league_name

我猜你只想把输赢算作“玩过”。

于 2013-11-09T21:26:54.490 回答