2012-04-09 98 views
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 

有什麼建議? 謝謝! 克里斯

+1

共享存儲在表中的數據的exapmle。 – 2012-04-09 06:18:23

回答

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:這是沒有意義的項目一年順序您已經在它聚集。

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