如何使用pivot转换表

时间:2016-06-28 12:53:12

标签: sql-server-2012

我有一组看起来像这样的数据: -

product        May_Qty    June_Qty
---------      ---        -----------
   p1           2         44
   p2           1         54
   p3           5         55

我希望结果如 :(使用数据透视)或其他方法

product        Month       Qty
---------      ---         -----------
       p1       May         2
       p1       June        44
       p2       May         1
       p2       June        54
       p3       May         5
       p3       June        55

1 个答案:

答案 0 :(得分:1)

我必须承认:整个设计都有点味道。通常它是相反的:数据在列表中,人们希望它作为透视(宽)列表用于显示目的。因此,考虑使用目前需要设计的表格......

如果你真的想坚持这一点,这里有两种产生相同输出的方法:

DECLARE @tbl TABLE(product VARCHAR(100),May_Qty INT,June_Qty INT);
INSERT INTO @tbl VALUES
 ('p1',2,44)
,('p2',1,54)
,('p3',5,55);

使用UNION ALL创建一个派生表,其值为list,然后对其进行排序

SELECT product,[Month],Qty
FROM
(
    SELECT product,5 AS MonthIndex,'May' AS [Month],May_Qty As Qty
    FROM @tbl 
    UNION ALL
    SELECT product,6,'June',June_Qty
    FROM @tbl 
) AS parted
ORDER BY product,MonthIndex;

UNPIVOT大致相同:

SELECT up.*
FROM 
(SELECT product, May_Qty AS May, June_Qty AS June FROM @tbl) AS tbl
UNPIVOT
(Qty FOR [Month] IN(May,June)) AS up