Pivot查询返回T-SQL中的所有值

时间:2017-11-09 09:01:29

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

我有一个要求,我想为我的表构建一个透视查询,在屏幕截图中显示。

这是我的表

enter image description here

我想将行值设为列。

我的尝试:

SELECT rno, NO,Description,CarNo,ID from 
             (
select row_number()over(partition by columnname order by rno)rno, columnname,value
                from mytable 
                group by rno, columnname,value
            ) x
            pivot 
            (
                max(value)
                for columnname in (NO,Description,CarNo,ID)
            ) p

实际输出:

enter image description here

预期产出:

NO      |   Description |   CradNo  |    ID
---------------------------------------------
Part1   |   desc1       |   Card1   |    1
Part2   |   desc2       |   Card1   |    1

1 个答案:

答案 0 :(得分:2)

你可以使用它。

DECLARE @mytable TABLE(columnname VARCHAR(20), value VARCHAR(10), rno INT)
INSERT INTO @mytable
VALUES
('ID', '1', 1),
('NO', 'Part1', 1),
('NO', 'Part2', 1),
('Description', 'desc1', 1),
('Description', 'desc2', 1),
('CarNo', 'car1', 1)

;WITH CTE AS 
(SELECT * FROM 
    (SELECT *, RN = ROW_NUMBER() OVER(PARTITION BY columnname Order BY rno, value) 
        FROM @mytable) SRC
PIVOT ( MAX(value) FOR columnName IN ([ID], [NO], [Description], [CarNo]) ) PVT
)
SELECT 
     ISNULL( T1.NO, T2.NO) NO
    , ISNULL( T1.Description, T2.Description) Description
    , ISNULL( T1.CarNo, T2.CarNo) CarNo
    , ISNULL( T1.ID, T2.ID) ID  
FROM CTE T1 OUTER APPLY ( SELECT TOP 1 * FROM CTE WHERE CTE.RN < T1.RN   ) T2

结果:

NO         Description CarNo      ID
---------- ----------- ---------- ----------
Part1      desc1       car1       1
Part2      desc2       car1       1