如何在SQL Server中将行转置为列?

时间:2019-06-06 19:59:24

标签: sql-server hana

我有以下代码,我想将多行转置为一列。

这是我的数据外观的一个示例:

DocNum    ItemCode  Item Name
-----------------------------------
40008      100208   Desc of 100208  /*parts*/
40008      100209   Desc of 100208  /*parts*/
40008      200845   Desc of 200845  /* tire*/
40008      320361   Desc of 320361  /* disc*/
40008      400511   Desc of 400511  /* rim*/

我正在寻找如下所示的结果

itemcode   rim/disc                  tire/parts    
------------------------------------------------
40008      400511-Desc of 400511     200845-Desc of 200845 
           320361-Desc of 320361     100208-Desc of 100208  
                                     100209-Desc of 100208  

这是我尝试过的SQL代码:

select top 10  
    T0.[DocNum], T0.[OriginNum], T0.[ItemCode], T0.[ProdName],     
    T2.[CardName], T0.[Status], T4.[U_Routing], T0.[PlannedQty], 
    T0.[CmpltQty], T0.[PostDate], T0.[DueDate],T1.[ItemCode], 
    T3.[ItemName], T0.[U_Work_Center], T0.[CreateDate]  
from  
    [SERVERNAME]..[DATABASE].[OWOR] as T0 
inner join 
    [SERVERNAME]..[DATABASE].[WOR1] T1 on T0.[DocEntry] = T1.[DocEntry] 
inner join 
    [SERVERNAME]..[DATABASE].[OCRD] T2 on T0.[CardCode] = T2.[CardCode] 
inner join
    [SERVERNAME]..[DATABASE].[OITM] T3 on T1.[ItemCode] = T3.[ItemCode] 
inner join
    [SERVERNAME]..[DATABASE]. [OITM] T4 on T0.[ItemCode] = T4.[ItemCode]

1 个答案:

答案 0 :(得分:0)

如您所提问题,您需要使用PIVOT表,请参阅以下link

在此处使用数据是一个示例:

CREATE TABLE ITEMS (DocNum INT, ItemCode NVARCHAR(MAX), ItemName NVARCHAR(MAX), ItemDesc NVARCHAR(MAX));

INSERT INTO ITEMS (DocNum, ItemCode, ItemName, ItemDesc)
VALUES (40008, '100208', 'Desc of 100208', 'Parts');

INSERT INTO ITEMS (DocNum, ItemCode, ItemName, ItemDesc)
VALUES (40008, '100209', 'Desc of 100209', 'Parts');

INSERT INTO ITEMS (DocNum, ItemCode, ItemName, ItemDesc)
VALUES (40008, '200845', 'Desc of 200845', 'Tire');

INSERT INTO ITEMS (DocNum, ItemCode, ItemName, ItemDesc)
VALUES (40008, '320361', 'Desc of 320361', 'Disc');

INSERT INTO ITEMS (DocNum, ItemCode, ItemName, ItemDesc)
VALUES (40008, '400511', 'Desc of 400511', 'Rim');

以下是数据透视表的示例:

SELECT 
  DocNum AS [DocNum], [Parts],[Tire],[Disc],[Rim]
FROM
  (
    SELECT 
      DocNum, ItemName, ItemDesc
    FROM ITEMS
   ) AS SOURCE
PIVOT
(
  MAX(ItemName) FOR ItemDesc IN ([Parts],[Tire], [Disc], [Rim])
)  AS Pivoted; 

您可能会注意到列名与列ItemDesc的数据相同。对于这种简单的情况而言,手动放置列名并不是一件难事,您可能需要创建一个存储过程来动态生成透视表,您可以在下面的link中看到如何做。

在这里您可以测试以下脚本:http://www.sqlfiddle.com/#!18/45f81/23/0并查看预期的结果。祝你好运!