首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >名列前茅的足球联赛

名列前茅的足球联赛
EN

Stack Overflow用户
提问于 2016-10-24 08:52:46
回答 1查看 726关注 0票数 1

我有两张桌子。第一表

代码语言:javascript
运行
复制
   id_klub    || nama_klub
      01      || manchester
      02      || chelsea
      03      || liverpool
      04      || arsenal

第二表

代码语言:javascript
运行
复制
 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张桌子上获得排名呢?

代码语言:javascript
运行
复制
club_name   ||game ||win    ||lose  ||draw  ||point
chelsea     || 2   ||0      || 1    || 1    || 1

with logic
win = point +3;
lose = point +0;
draw = point +1;

我尝试过这个查询

代码语言:javascript
运行
复制
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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-10-24 10:15:54

您需要在game表上加入两次klub表,一次在home上,一次在away字段上,以获得团队参与的所有游戏。

然后,您需要将两个表中的条件计数相加,以获得预期的输出,如下面的代码所示。

代码语言:javascript
运行
复制
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
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40214273

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档