我想在Oracle和/或使用Pivot函数的SQL Server中使用Pivot函数将行转置为列。我的用例与此Efficiently convert rows to columns in sql server非常相似 但是,我正在按特定的数据类型组织数据(在StringValue和NumericValue下面显示)。
这是我的示例:
Const
这是我的结果:
----------------------------------------------------------------------
| Id | Person_ID | ColumnName | StringValue | NumericValue |
----------------------------------------------------------------------
| 1 | 1 | FirstName | John | (null) |
| 2 | 1 | Amount | (null) | 100 |
| 3 | 1 | PostalCode | (null) | 112334 |
| 4 | 1 | LastName | Smith | (null) |
| 5 | 1 | AccountNumber | (null) | 123456 |
----------------------------------------------------------------------
如何构建SQL查询?
我已经尝试在Oracle中使用MAX(DECODE())和CASE语句。但是性能非常差。寻找Oracle和/或SQL Server中的数据透视功能是否可以更快地完成此任务。还是应该转到单列值?
答案 0 :(得分:0)
下面的代码将满足您的要求
Create table #test
(id int,
person_id int,
ColumnName varchar(50),
StringValue varchar(50),
numericValue varchar(50)
)
insert into #test values (1,1,'FirstName','John',null)
insert into #test values (2,1,'Amount',null,'100')
insert into #test values (3,1,'PostalCode',null,'112334')
insert into #test values (4,1,'LastName','Smith',null)
insert into #test values (5,1,'AccountNumber',null,'123456')
--select * from #test
Declare @Para varchar(max)='',
@Para1 varchar(max)='',
@main varchar(max)=''
select @Para += ','+QUOTENAME(ColumnName)
from (select distinct ColumnName from #test) as P
set @Para1= stuff(@para ,1,1,'')
print @Para1
set @main ='select * from (
select coalesce(StringValue,numericValue) as Val,ColumnName from #test) as Main
pivot
(
min(val) for ColumnName in ('+@Para1+')
) as pvt'
Exec(@main)