TSQL Pivot查询

时间:2016-02-05 16:36:29

标签: sql-server tsql pivot dynamic-sql

我需要TSQL Pivot的帮助并收到错误。任何帮助是极大的赞赏。 以下是查询和数据。

DECLARE @cols AS VARCHAR(8000),
    @query  AS VARCHAR(8000)

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.steps) 
            FROM Tableabc AS c
            FOR XML PATH(''), TYPE
            ).value('.', 'VARCHAR(8000)') 
        ,1,1,'')
--print @cols
set @query = 'SELECT name, ElapsedTime_Sec,' + @cols + ' from 
            (
                select name,ElapsedTime_Sec

                FROM Tableabc
           ) x
            pivot 
            (
                 max(steps)
                for ElapsedTime_Sec in (' + @cols + ')
            ) p '


execute(@query)

表格信息:

Table Info

1 个答案:

答案 0 :(得分:1)

没有任何预期的输出和错误的PIVOT查询,我只是猜测你想要什么。但这是一个基于你的问题松散工作的脚本。我猜它不是你想要的输出,但你可以从这个脚本开始工作,也许可以把它变成你需要的东西。

CREATE TABLE #Tableabc(ID INT,name VARCHAR(256), Steps VARCHAR(1024),ElapsedTime_Sec INT);

INSERT INTO #Tableabc(ID,name,Steps,ElapsedTime_Sec)VALUES
    (2,'Features','Touch/Stain',25),
    (29,'Shipping','Step requiring QA',129),
    (47,'Behavioral','Gloves',8);

DECLARE @cols AS VARCHAR(8000),
    @query  AS VARCHAR(8000);

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.steps) 
            FROM #Tableabc AS c
            FOR XML PATH(''), TYPE
            ).value('.', 'VARCHAR(8000)') 
        ,1,1,'')

set @query = 'SELECT * FROM #Tableabc
            pivot 
            (
                 max(ElapsedTime_Sec)
                for Steps in (' + @cols + ')
            ) p ';
execute(@query);

DROP TABLE #Tableabc;

输出:

+----+------------+--------+-------------------+-------------+
| ID |    name    | Gloves | Step requiring QA | Touch/Stain |
+----+------------+--------+-------------------+-------------+
| 47 | Behavioral | 8      | NULL              | NULL        |
|  2 | Features   | NULL   | NULL              | 25          |
| 29 | Shipping   | NULL   | 129               | NULL        |
+----+------------+--------+-------------------+-------------+