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 に答える