在sql server中使用pivot转置行和列

时间:2013-08-06 09:01:08

标签: sql-server sql-server-2008 pivot

select planttype ,sum(noof50kgsbags*50)[50 Kg],sum(noof70kgsbags*70)[70 Kg]
from K_FeedPlantEntryIndent
WHERE  (date BETWEEN '2013-04-01 00:00.000' AND getdate()) AND (attrited = 'True')
group by planttype order by planttype

输出:

planttype   [50 Kg Bags]
Rohini        56150
Sneha         43950
KJL           353550
Suguna       1290850

期望输出::

Bags    Rohini   Sneha   KJL   Suguna
 50KgBags    x        xx     xx    xxx

使用Pivot我的查询::

select * from (select planttype  ,sum(noof50kgsbags*50)[50 Kg] from       K_FeedPlantEntryIndent WHERE  (date BETWEEN '2013-04-01 00:00.000' AND getdate()) AND   (attrited = 'True')
group by planttype)as t
PIVOT
( sum([50 Kg])
for[planttype] in( Rohini,Sneha,KJL,Suguna )
) As t2

此查询的结果:

    Rohini   Sneha   KJL   Suguna
     x        xx     xx    xxx

我也需要包包,因为我收到了错误。请帮帮我

1 个答案:

答案 0 :(得分:1)

试试这个:

select '50KgBags' [Bags], * from (select planttype  ,sum(noof50kgsbags*50)[50 Kg] from       K_FeedPlantEntryIndent WHERE  (date BETWEEN '2013-04-01 00:00.000' AND getdate()) AND   (attrited = 'True')
group by planttype)as t
PIVOT
( sum([50 Kg])
for[planttype] in( Rohini,Sneha,KJL,Suguna )
) As t2

SQLFiddle