【问题标题】:Join 2 different counts from 2 different tables into one subtable in sql将来自 2 个不同表的 2 个不同计数连接到 sql 中的一个表中
【发布时间】:2022-11-20 04:18:51
【问题描述】:

我有一个问题,我想计算一个国家从个人和团体比赛中总共赢得了多少奖牌,这并不能给我带来不利的结果。到目前为止我已经设法想出了这个。

select distinct C.Cname as Country, count(i.medal) as Medals_Won
from individual_results as i, Country as C, participant as p 
where (i.Olympian = p.OlympicID and C.Cname = p.country) 

union 

select distinct C.Cname, count(r.medal) as medals_Won
from team_results as r, Country as C, participant as p, team as t
where (r.team = t.TeamID and t.Member1 = p.OlympicID and C.Cname = p.Country)


group by C.Cname
order by medals_won desc

enter image description here

但我得到了这个结果。

即使我运行这两段单独的代码,我也会得到想要的结果,即enter image description here

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

    您应该对按 cname 分组的每个子查询的联合结果求和

        select t.Cname , sum( t.Medals_Won)
        from (
    
            select  C.Cname as Country, count(i.medal)  Medals_Won
            from individual_results  i 
            inner join  participant  p  ON i.Olympian = p.OlympicID 
            inner join Country  C ON C.Cname = p.country
            group by C.Cname
    
            union 
    
            select distinct C.Cname, count(r.medal) 
            from team_results as r
            inner join team as t ON r.team = t.TeamID
            inner join  participant as p ON t.Member1 = p.OlympicID
            inner join Country as C ON C.Cname = p.Country
            group by C.Cname
    
        ) t 
        group by t.Cname
        order by t.medals_won desc
    

    【讨论】:

      猜你喜欢
      • 2013-11-11
      • 1970-01-01
      • 2013-07-04
      • 1970-01-01
      • 2021-11-02
      • 2017-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多