假设您在垂直显示的时间内对个人进行了重复测量,并且您希望将其转换为宽显示,例如从
family | year | salary
fam1 | 2002 | 80
fam1 | 2003 | 82
fam1 | 2008 | 90
fam2 | 1996 | 45
fam3 | 2002 | 70
fam3 | 2003 | 72
到
family | salary1996 | salary2002 | salary2003 | salary2008
fam1 | 45 | . | . | .
fam2 | . | 80 | 82 | 90
fam3 | . | 70 | 72 | .
问题是“年”有任意数量的可能值。
答案 0 :(得分:3)
如果您使用的是SQL Server,那么您正在寻找:
<强>更新强>
仍然假设您使用的是SQL Server 2005或更高版本,以下是代码:
DECLARE @cols VARCHAR(1000)
DECLARE @sqlquery VARCHAR(2000)
SELECT @cols = STUFF(( SELECT distinct '], [' + cast([year] as varchar)
FROM YourTable FOR XML PATH('') ), 1, 2, '') + ']'
SET @sqlquery = 'SELECT * FROM
(SELECT family, [year], [salary]
FROM YourTable) base
PIVOT (SUM(salary) FOR [year]
IN (' + @cols + ')) AS finalpivot'
EXECUTE ( @sqlquery )