交换列和行

时间:2015-03-08 11:42:49

标签: sql-server tsql

我有这样一张桌子:

a  |  b  |  c
-------------
1  |  2  |  3

其中第一行是列名。我想将整个表和converto交换到:

col  |  val
-----------
a    |  1
b    |  2
c    |  3

如何通过T-SQL中的Unpivot执行此操作?

2 个答案:

答案 0 :(得分:1)

试试这个:

--Create YourTable
SELECT  1 AS a,
        2 AS b,
        3 AS c INTO YourTable

--Unpivot YourTable
SELECT  unpvt.Col,
        unpvt.Val
FROM YourTable
UNPIVOT 
    (Val for Col in (a,b,c)) unpvt

答案 1 :(得分:1)

如果您有多种数据类型,则可以将列转换为NVARCHAR,因为大多数数据类型都可以像NVARCHAR一样转换为:

   --Create YourTable
SELECT  N'unicode text' AS a,
        CAST(23123123 AS BIGINT)AS b,
        CAST('20120101' AS DATE) AS c INTO YourTable

--Unpivot YourTable
SELECT  unpvt.Col,
        unpvt.Val
FROM 
--Cast each column as NVARCHAR
(
    SELECT  CAST(a AS NVARCHAR(MAX)) a,
            CAST(b AS NVARCHAR(MAX)) b,
            CAST(c AS nvarchar(MAX)) c
    FROM YourTable
) A
UNPIVOT 
    (Val for Col in (a,b,c)) unpvt

DROP TABLE YourTable