数据透视表 - 需要包含空值为null

时间:2013-05-01 14:59:16

标签: mysql pivot-table

我正在尝试使用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:

这仅适用于具有所有“YEAR”值的“WMU”条目。例如,根本不会选择例如b中的行。

有什么方法可以修改这个语句,以便空白年份值在输出中显示为空?

提前致谢!

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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