使用pivot将select转换为一列,而不是一行

6tdlim6h  于 2021-08-13  发布在  Java
关注(0)|答案(1)|浏览(375)

我试图做一个select,它将结果显示为一列,而不是一行。我试过用 PIVOT ,但我一点也不成功。
我的选择结果:

Customer_ID:   InsertionDate:  Name:   Birth:                                                
  1234          2020-01-01     John  1993-01-01

我想要这样:

MyColumn                                               
 Customer_ID:    1234   
 InsertionDate:  2020-01-01  
 Name:           John  
 Birth:          1993-01-01
r8uurelv

r8uurelv1#

你可以用 cross apply 要获得单个列:

declare @test table (Customer_ID int,  InsertionDate date,  Name varchar(50), Birth date)   
insert into @test values (1234, '2020-01-01','John', '1993-01-01')

select  val as MyColumn
from @test
    CROSS APPLY 
    (
    VALUES
        ('Customer_ID:'+   cast(Customer_ID as varchar)),
        ('InsertionDate:'+ cast(InsertionDate as varchar)),
        ('Name:'+ cast(Name as varchar)),
        ('Birth:'+ cast(Birth as varchar))
    )CS (val)

结果:

或者,如果您更喜欢使用单独的列来描述:

select 
    Col as ColumnName, 
    val as MyColumn
from @test
    CROSS APPLY 
    (
    VALUES
        ('Customer_ID:'  , cast(Customer_ID as varchar)),
        ('InsertionDate:', cast(InsertionDate as varchar)),
        ('Name:'         , cast(Name as varchar)),
        ('Birth:'        , cast(Birth as varchar))
    )CS (col, val)

输出:

相关问题