1

我有一张表格,上面有国家、年份和每年的金额。我正在尝试编写一个查询,将给定年份的总金额相加并将其作为一列提供给我。

例如,要具有如下所示的输出:

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

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

4

2 回答 2

0

Give this a try:

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: It makes no sense to order by project year as you're already aggregating on it.

于 2012-04-09T06:20:09.657 回答
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
于 2012-04-09T06:22:35.460 回答