2013-05-01 31 views
1

我試圖使用MySQL來改變修改(透視)表:透視表 - 需要包含空值作爲空

WMU  YEAR  CPUE 
a  1987  22 
a  1988  32 
a  1989  2 
a  1990  34 
b  1988  5 
b  1990  4 

需要是:

WMU  CPUE_1987  CPUE_1988 CPUE_1999 CPUE_1990 
a   22   32   2    34 
b   5   null  null   4 

我曾嘗試使用SELECT和JOIN聲明:

select t.wmu, 
tb2.CPUE as CPUE_1987, 
tb3.CPUE as CPUE_1988, 
tb4.CPUE as CPUE_1989, 
tb5.CPUE as CPUE_1990, 
from muledeerharvest2011 as t 
JOIN muledeerharvest2011 as tb2 
JOIN muledeerharvest2011 as tb3 
JOIN muledeerharvest2011 as tb4 
JOIN muledeerharvest2011 as tb5 
WHERE tb2.year = 1987 and t.WMU = tb2.WMU 
and tb3.year = 1988 and t.WMU = tb3.WMU 
and tb4.year = 1989 and t.WMU = tb4.WMU 
and tb5.year = 1990 and t.WMU = tb5.WMU: 

這個只適用於擁有所有的「年」值「西密歇根大學」的條目。在這個例子中,諸如b的行將不會被選中。

有什麼辦法可以修改此語句,以便空白年份值在輸出中顯示爲空?

在此先感謝!

回答

0

如果我得到問題正確,那麼下面的查詢將爲您解決問題。

你沒有得到和值,因爲你是INNER JOIN (JOIN)LEFT JOIN將做trcik

select distinct 
t.wmu, 
tb2.CPUE as CPUE_1987, 
tb3.CPUE as CPUE_1988, 
tb4.CPUE as CPUE_1989, 
tb5.CPUE as CPUE_1990 
from muledeerharvest2011 as t 
LEFT JOIN muledeerharvest2011 tb2 
    on tb2.Year = 1987 and t.WMU = tb2.WMU 
LEFT JOIN muledeerharvest2011 tb3 
    on tb3.Year = 1988 and t.WMU = tb3.WMU 
LEFT JOIN muledeerharvest2011 tb4 
    on tb4.Year = 1989 and t.WMU = tb4.WMU 
LEFT JOIN muledeerharvest2011 tb5 
    on tb5.Year = 1990 and t.WMU = tb5.WMU 

這裏是SQL Fiddle

+0

完美的作品!非常感謝你的幫助! – Rozza 2013-05-01 16:12:41

0

這也可以使用具有CASE表達式集合函數寫爲:

select wmu, 
    sum(case when year=1987 then cpue end) CPUE_1987, 
    sum(case when year=1988 then cpue end) CPUE_1988, 
    sum(case when year=1989 then cpue end) CPUE_1989, 
    sum(case when year=1990 then cpue end) CPUE_1990 
from muledeerharvest2011 
group by wmu; 

參見SQL Fiddle with Demo