【发布时间】:2012-07-07 09:44:14
【问题描述】:
SQL 2005
我有一个临时表:
Year PercentMale PercentFemale PercentHmlss PercentEmployed TotalSrvd
2008 100 0 0 100 1
2009 55 40 0 80 20
2010 64 35 0 67 162
2011 69 27 0 34 285
2012 56 43 10 1 58
我想创建一个查询来显示这样的数据:
2008 2009 2010 2011 2012
PercentMale 100 55 64 69 56
PercentFemale - 40 35 27 43
PercentHmlss - - - - 10
PercentEmployed 100 80 67 34 1
TotalSrvd 1 20 162 285 58
我可以使用数据透视表来完成此操作吗?如果是这样,怎么做?我试过使用支点,但没有成功。
select PercentHmlss,PercentMale,Percentfemale,
PercentEmployed,[2008],[2009],[2010],[2011],[2012] from
(select PercentHmlss,PercentMale, Percentfemale, PercentEmployed,
TotalSrvd,year from @TempTable)as T
pivot (sum (TotalSrvd) for year
in ([2008],[2009],[2010],[2011],[2012])) as pvt
这是结果:
PercentHmlss PercentMale Percentfemale PercentEmployed [2008] [2009] [2010] [2011] [2012]
0 55 40 80 NULL 20 NULL NULL NULL
0 64 35 67 NULL NULL 162 NULL NULL
0 69 27 34 NULL NULL NULL 285 NULL
0 100 0 100 1 NULL NULL NULL NULL
10 56 43 1 NULL NULL NULL NULL 58
谢谢。
【问题讨论】:
-
你还没说是什么问题。
No success不是描述。你收到错误信息了吗? *(例如,您似乎在PercentEmployed[2008]中间缺少,。)或者您是否获得了数据,而不是您预期的数据?
标签: sql sql-server-2005 pivot unpivot