表在sql server中转置?

时间:2012-03-15 00:59:08

标签: sql sql-server-2008

我尝试编写sql代码来创建一个表,它是给定表的转置。最初我有一个数据表。我正在尝试创建一个使用sql server management studio转换输入表的表。

Plz帮助我......

输入如下: tbl

输出:

tbltr

2 个答案:

答案 0 :(得分:1)

答案 1 :(得分:0)

这样的事情可能会起到作用:

测试数据

CREATE TABLE #tbl 
    (
        Y1 INT,
        Y2 INT,
        Y3 INT,
        Y4 INT,
        Y5 INT
    )

INSERT INTO #tbl
VALUES
    (1,2,3,4,9),
    (1,6,9,3,6),
    (2,2,6,7,6)

然后我们需要知道那里有多少X列。这得到了列:

DECLARE @nbrOf INT=(SELECT COUNT(*) FROM #tbl)

DECLARE @cols VARCHAR(MAX)
DECLARE @colsWithName VARCHAR(MAX)

;WITH Nbrs ( n ) AS (
        SELECT 1 UNION ALL
        SELECT 1 + n FROM Nbrs WHERE n <@nbrOf )
SELECT
    @cols = COALESCE(@cols + ','+QUOTENAME(n),
                     QUOTENAME(n)),
    @colsWithName = COALESCE(@colsWithName + ','+QUOTENAME(n)+' AS X'+CAST(n AS VARCHAR(10)),
                     QUOTENAME(n)+' AS X'+CAST(n AS VARCHAR(10)))
FROM
    Nbrs

然后我们将使用pivot来做一些动态sql。像这样:

DECLARE @query NVARCHAR(4000)=
N'SELECT
    '+@colsWithName+'
FROM
    (
        SELECT
            ROW_NUMBER() OVER(ORDER BY tbl.Y1) AS RowNbr,
            tbl.Y1,
            tbl.Y2,
            tbl.Y3,
            tbl.Y4,
            tbl.Y5
        FROM
            #tbl AS tbl
    ) AS p
    UNPIVOT
    (
        Value FOR Name IN 
      (Y1, Y2, Y3, Y4, Y5)
    ) AS unpvt
    PIVOT
    (
        MAX(Value)
        FOR RowNbr IN('+@cols+')
    ) AS pvt'
EXECUTE(@query)

然后在我的情况下,我将删除临时表

DROP TABLE #tbl