数据透视表 [英] Pivot table
问题描述
大家好,
我有Microsoft SQL Server 2008 R2(SP1) - 10.50.2550.0(英特尔X86) 2012年6月11日17:46:13 版权所有(c)Microsoft Corporation Windows NT 6.1上的标准版< X86> (Build 7601:Service Pack 1)
I have Microsoft SQL Server 2008 R2 (SP1) - 10.50.2550.0 (Intel X86) Jun 11 2012 17:46:13 Copyright (c) Microsoft Corporation Standard Edition on Windows NT 6.1 <X86> (Build 7601: Service Pack 1)
有此表:
Have this table:
选择'姓名'问题,'亚历克斯史密斯'答复工会全部为
选择'类型','销售'工会全部为
选择'来源','其他'union all
选择'公司名称','SEW'工会全部为
选择'账户类型','34 -FT SST'工会全部为
选择'今天的日期','01/01/2019'
$
select 'Name' question, 'Alex Smith' answer union all
select 'Type', 'Sales' union all
select 'Source', 'Other' union all
select 'Company Name', 'SEW' union all
select 'Account Type', '34-FT SST' union all
select 'Date today', '01/01/2019'
我需要得到这样的结果:
I need get this result:
谢谢!
Thank you!
推荐答案
;With mycte as (
Select *, row_number() Over(Order by question) rn from (select 'Name' question, 'Alex Smith' answer union all
select 'Type', 'Sales' union all
select 'Source', 'Other' union all
select 'Company Name', 'SEW' union all
select 'Account Type', '34-FT SST' union all
select 'Date today', '01/01/2019') t
)
Select 'question' as col1,max(Case when rn=1 then question else null end) col2
,max(Case when rn=2 then question else null end) col3
,max(Case when rn=3 then question else null end) col4
,max(Case when rn=4 then question else null end) col5
,max(Case when rn=5 then question else null end) col6
,max(Case when rn=6 then question else null end) col7
from mycte
Union all
Select 'answer' as col1, max(Case when rn=1 then answer else null end) col2
,max(Case when rn=2 then answer else null end) col3
,max(Case when rn=3 then answer else null end) col4
,max(Case when rn=4 then answer else null end) col5
,max(Case when rn=5 then answer else null end) col6
,max(Case when rn=6 then answer else null end) col7
from mycte
这篇关于数据透视表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!