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:

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

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

提前致谢!

4

2 回答 2

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

于 2013-05-01T16:16:23.463 回答
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 小提琴

于 2013-05-01T15:15:21.537 回答