【问题标题】:Transpose of rows and columns using pivot in sql server使用 sql server 中的数据透视表转置行和列
【发布时间】:2013-08-06 09:01:07
【问题描述】:
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

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

【问题讨论】:

  • 能否提供错误信息?
  • @Andrey 不完全是一个指定的错误我得到不同的 O/P
  • 让我澄清一下:您的问题是您缺少 Bags 列?
  • @Andrey 是的。通过添加 Bags 列,我得到了不同的输出

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


【解决方案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

【讨论】:

    猜你喜欢
    • 2021-12-17
    • 2023-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多