如何将列转换为行?

时间:2012-02-10 02:27:27

标签: sql sql-server pivot unpivot

我有一张像这样的桌子

RowNum | TranNo | nTotalSales | nBalance
   1   |    1   |    800      |    0

我希望以这种方式显示

RowNum      |   1
cTranNo     |   1
nTotalSales |  800
nBalance    |   0

我该怎么做?

3 个答案:

答案 0 :(得分:2)

这是一个完整的工作示例,当您执行UNPIVOT时,您的要求是什么,您的“价值”类型必须属于同一类型,因此您可以根据需要进行投射。在我的例子中,我将它们全部转换为VARCHAR(20):

DECLARE @bob TABLE
(
    RowNum INT,
    TranNo INT,
    nTotalSales INT,
    nBalance INT
);
INSERT INTO @bob(RowNum, TranNo, nTotalSales, nBalance)
VALUES(1, 1, 800, 0);


WITH T AS (
    SELECT CAST(RowNum      AS VARCHAR(20)) AS RowNum,
           CAST(TranNo      AS VARCHAR(20)) AS TranNo,
           CAST(nTotalSales AS VARCHAR(20)) AS nTotalSales,
           CAST(nBalance    AS VARCHAR(20)) AS nBalance
    FROM @bob
)

SELECT attribute, value
FROM T
UNPIVOT(value FOR attribute IN(RowNum, TranNo, nTotalSales, nBalance)) AS U;

答案 1 :(得分:1)

SELECT 'RowNum' TITLE, RowNum AS [VALUE]
FROM TABLE
UNION ALL
SELECT 'TranNo', TranNo
FROM TABLE
UNION ALL
SELECT 'nTotalSales', nTotalSales
FROM TABLE
UNION ALL
SELECT 'nBalance', nBalance
FROM TABLE

答案 2 :(得分:1)

这不是真正的乐趣,但这是一个解决方案:

SELECT 'RowNum', RowNum FROM tbl
UNION
SELECT 'cTranNo', TranNo FROM tbl
UNION
SELECT 'nTotalSales', nTotalSales FROM tbl
UNION
SELECT 'nBalance', nBalance FROM tbl

这将把列变成行。如果您希望每个列行都是隔行扫描的,则可能需要引入一个记录编号以及一些排序。

看起来像这样:

    SELECT 'RowNum' AS ColName, RowNum AS [Value], RowNum FROM tbl
    UNION
    SELECT 'cTranNo' AS ColName, TranNo, RowNum FROM tbl
    UNION
    SELECT 'nTotalSales' AS ColName, nTotalSales, RowNum FROM tbl
    UNION
    SELECT 'nBalance' AS ColName, nBalance, RowNum FROM tbl
    ORDER BY RowNum, ColName