具有列名称的数据透视表

时间:2016-07-01 07:15:01

标签: sql sql-server unpivot

如果你有一张桌子(例子)

   declare @MyTable table (
CustomerName nvarchar(50),
BirthDate datetime,
BirtPlace nvarchar(50),
Phone nvarchar(50),
Email nvarchar(50)
)

insert into @MyTable
        (
         CustomerName,
         BirthDate,
         BirtPlace,
         Phone,
         Email
        )
values  (
         'Customer1', 
         '12.05.1990', 
         'Place1', 
         N'+000125456789', 
         N'customer@customer.com' 
        )

是否可以获得以下结果集:

    CustomerName   Customer1
    BirtDate       1990-12-05 
    BirtPlace      Place1
    Phone          +000125456789
    Email          customer@customer.com 

像枢轴这样的东西,但我不知道如何得到这个结果。

4 个答案:

答案 0 :(得分:3)

如果要将列更改为行,则所需的功能为unpivot而不是pivot

这应该可以解决问题:

SELECT col, val
FROM 
( 
    SELECT 
        CustomerName, 
        CAST(BirthDate AS NVARCHAR(50)) BirthDate, 
        BirtPlace, 
        Phone, 
        Email  
    FROM @MyTable
) AS t
UNPIVOT 
(
    val FOR col IN (CustomerName, BirthDate, BirtPlace, Phone, Email)
) AS u

答案 1 :(得分:2)

试试这个

SELECT myColumn, myDetail    
FROM
(
    SELECT
        CustomerName,
        CONVERT(NVARCHAR(50),BirthDate,121) AS BirthDate,
        BirtPlace,
        Phone,
        Email
    FROM
        @MyTable
) AS A
UNPIVOT
(
    myDetail FOR myColumn IN (CustomerName, BirthDate, BirtPlace, Phone, Email)
) AS tbUnpivot

答案 2 :(得分:0)

这是一个unpivot问题,如果你使用旧版本的sql server 2000,这个unpivot语法将不起作用,那么你可以使用UNION

SELECT 'CustomerName' AS colName, CustomerName AS colVal FROM @MyTable
UNION
SELECT 'BirthDate' AS colName, CAST(BirthDate AS NVARCHAR(50)) AS colVal FROM @MyTable
UNION
SELECT 'BirthPlace' AS colName, BirthPlace AS colVal FROM @MyTable
UNION
SELECT 'Phone' AS colName, Phone AS colVal FROM @MyTable
UNION
SELECT 'Email' AS colName, Email AS colVal FROM @MyTable;

答案 3 :(得分:-1)

 SELECT CustomerName,BirtDate,BirtPlace,Phone,Email FROM @MyTable\G 

您没有身份证,也没有外键,所以我认为这是一种解决问题的方法。 \ G为您提供SQL查询作为列表。

  values  (
     'Customer1', '1990-12-05', 'Place1', '+000125456789', 'customer@customer.com' 
    );

我希望我能帮到你

度过愉快的一天