查询我的sql db

时间:2016-02-05 14:19:18

标签: mysql sql

我有两个不同的查询:

SELECT Nazione,
       count(*) as Gold
  FROM `SummerTotalMedal` 
 where Medaglia = 'gold'
   and Sport = 'Athletics' 
 group by Nazione
 order by Gold DESC

SELECT Nazione, 
       count(*) as Silver
  FROM `SummerTotalMedal` 
 where Medaglia = 'silver'
   and Sport = 'Athletics' 
 group by Nazione
 order by Silver DESC

有没有办法加入这个查询,以便在两个不同的颜色上获得两个不同的输出?

2 个答案:

答案 0 :(得分:3)

您可以对相同的

使用条件聚合
select 
Nazione,
sum(case when Medaglia ='gold' and Sport='Athletics' then 1 else 0 end) as Gold,
sum(case when Medaglia ='silver' and Sport='Athletics' then 1 else 0 end) as Silver
from SummerTotalMedal
group by Nazione

答案 1 :(得分:0)

MySQL中有IF函数:

SELECT Nazione,
    sum(IF(Medaglia ='gold', 1, 0)) as Gold,
    sum(IF(Medaglia ='silver', 1, 0)) as Silver
FROM SummerTotalMedal
WHERE Sport='Athletics'
GROUP BY Nazione