将列从2个表转换为行

时间:2016-08-17 01:08:28

标签: sql sql-server tsql sql-server-2012

我有一个连接2个表的查询,我从2个表中得到的查询是:

SELECT A.ID,A.CSTID,B.OCT,B.NOV,B.DEC
FROM TBL A 
INNER JOIN TBL B ON A.ID = B.NUM

以上查询的输出为:

ID   CSTID  OCT  NOV  DEC
--------------------------
1    1A     20   25   30

我希望输出为:

ID   CSTID  MONTHS  VALUE
-------------------------
1    1A     OCT     20
1    1A     NOV     25
1    1A     DEC     30

我使用了以下查询,但收到错误:

SELECT 
    A.ID, A.CSTID,
    C.MONTHS,
    C.VALUE
FROM 
    TBL A 
INNER JOIN 
    TBL B ON A.ID = B.NUM
UNPIVOT 
   (VALUE FOR MONTHS IN (OCT, NOV, DEC)) C

3 个答案:

答案 0 :(得分:2)

使用select * from ...包围已结合的结果并使用unpivot

SELECT * FROM (
SELECT A.ID,A.CSTID,B.OCT as october,B.NOV as november, B.DEC
as december 
 FROM TBL A 
INNER JOIN TBL B ON A.ID = B.NUM ) T
UNPIVOT (
         VALUE FOR MONTHS IN (october,november,december)
        ) C

答案 1 :(得分:0)

使用UNPIVOT

SELECT ID,
       CSTID,
       MonthName AS MONTHS,
       Month AS VALUE
FROM
(
    SELECT A.ID,
           A.CSTID,
           B.OCT AS OCTOBER,
           B.NOV AS NOVEMBER,
           B.DEC AS DECEMBER
    FROM TBL A 
    INNER JOIN TBL B
        ON A.ID = B.NUM
) t1
UNPIVOT
(
    Month FOR MonthName IN (OCTOBER, NOVEMBER, DECEMBER)
) AS t2

<强>注释:

我在原始查询中看到的唯一问题是您没有将连接包装在括号中并为其指定别名。如果我的解决方案适合您,那么您将知道情况就是这样。

答案 2 :(得分:0)

你必须做这样的事情:

SELECT * INTO TBL FROM (
VALUES(1, '1A',1,20,25,30)) as x(ID, CSTID, Num, OCT,  NOV,  DEC)

SELECT A.ID, A.CSTID, tt.Month_Name, tt.Month_Value
FROM TBL as A
INNER JOIN TBL as B
ON A.ID = B.NUM
CROSS APPLY (VALUES
    (B.OCT, 'OCT'), (B.NOV, 'NOV'), (B.DEC, 'DEC')
) tt (Month_Value, Month_Name)