我有两张桌子。第一表
id_klub || nama_klub
01 || manchester
02 || chelsea
03 || liverpool
04 || arsenal
第二表
id_skor || Date || Home || Away || skor_home|| skor_away
0001 || 12/12/12 || 01 || 02 || 3 || 2
0002 || 13/12/12 || 02 || 03 || 2 || 2
0003 || 14/12/12 || 04 || 03 || 1 || 3
0004 || 15/12/12 || 04 || 01 || 3 || 1
在第二个表“家”和“离开”中,表示id_club,例如:
当主场= 01和客场= 02的时候,这意味着曼彻斯特对雪莉,而我的问题是,我怎么能从那2张桌子上获得排名呢?
club_name ||game ||win ||lose ||draw ||point
chelsea || 2 ||0 || 1 || 1 || 1
with logic
win = point +3;
lose = point +0;
draw = point +1;
我尝试过这个查询
SELECT nama_klub,
count(case when skor_home > skor_away then 1 end) wins,
count(case when skor_home < skor_away then 1 end) lose,
count(case when skor_home = skor_away then 1 end) draw,
sum(
case when skor_home > skor_away then 3 else 0 end
+ case when skor_home = skor_away then 1 else 0 end
) score
FROM klub INNER JOIN game ON klub.id_klub = game.home
GROUP BY id_skor
发布于 2016-10-24 10:15:54
您需要在game
表上加入两次klub
表,一次在home
上,一次在away
字段上,以获得团队参与的所有游戏。
然后,您需要将两个表中的条件计数相加,以获得预期的输出,如下面的代码所示。
select nama_klub,
count(g1.home) + count(g2.away) as 'game',
count(if(g1.skor_home>g1.skor_away,1,null)) + count(if(g2.skor_home<g2.skor_away,1,null)) as win,
count(if(g1.skor_home=g1.skor_away,1,null)) + count(if(g2.skor_home=g2.skor_away,1,null)) as draw,
count(if(g1.skor_home<g1.skor_away,1,null)) + count(if(g2.skor_home>g2.skor_away,1,null)) as loss,
(count(if(g1.skor_home>g1.skor_away,1,null)) + count(if(g2.skor_home<g2.skor_away,1,null))) * 3 + (count(if(g1.skor_home=g1.skor_away,1,null)) + count(if(g2.skor_home=g2.skor_away,1,null))) as score
from klub k
left join game g1 on k.id_klub=g1.home
left join game g2 on k.id_klub=g2.away
group by k.id_klub, k.nama_klub
https://stackoverflow.com/questions/40214273
复制相似问题