选择给定年份的金额

时间:2012-04-09 06:14:51

标签: mysql

我有一张表,列出了每年的国家,年份和金额。我正在尝试编写一个查询,该查询将对给定年份的总金额求和,并将其作为列提供给我。

例如,要使输出看起来像:

Country   1991     1992     1993
France     25       12       38

我尝试了这样的查询,但无济于事:

SELECT 
     country as "Recipient", 
     SUM(usd_amount) AS "1991" WHEN project_year = 1991,
     SUM(usd_amount) AS "1992" WHEN project_year = 1992,
     SUM(usd_amount) AS "1993" WHEN project_year = 1993

FROM tb1

GROUP BY project_year, country
order by country, project_year

有什么建议吗? 谢谢! 克里斯

2 个答案:

答案 0 :(得分:0)

尝试一下:

SELECT 
     country as "Recipient", 
     SUM(if(project_year = 1991, usd_amount, 0)) AS "1991",
     SUM(if(project_year = 1992, usd_amount, 0)) AS "1992",
     SUM(if(project_year = 1993, usd_amount, 0)) AS "1993",
FROM tb1
GROUP BY country
ORDER BY country

PS:根据项目年度订购是没有意义的,因为您已经在聚合它。

答案 1 :(得分:0)

尝试以下

SELECT 
     country as "Recipient", 
     SUM(case WHEN project_year = 1991 then usd_amount else 0 end) AS "1991" ,
     SUM(case WHEN project_year = 1992 then usd_amount else 0 end) AS "1992" ,
     SUM(case WHEN project_year = 1993 then usd_amount else 0 end) AS "1993" 

FROM tb1

GROUP BY country, project_year
order by country, project_year