How to convert columns to rows?

旧城冷巷雨未停 提交于 2019-12-13 07:27:22

问题


I have a table like this one

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

and I want to display it this way

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

How can I do this?


回答1:


Here is a complete working example, when you you do an UNPIVOT, which is what your are asking for, your 'value' types need to be of the same type, so cast them however you want. In my example, I have cast them all to 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;



回答2:


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



回答3:


It's not real fun, but here's one solution:

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

That will turn the columns into rows. If you want each of the column-rows to be interlaced, you may need to introduce a record number along with some sorting.

That would look like this:

    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


来源:https://stackoverflow.com/questions/9221922/how-to-convert-columns-to-rows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!