尝试在SQL Server中将行转换为多列,如下所示:
当前结果:
PortCode CarCode
------------------------
AAB A5
ADR BH
SAN QQ
预期结果:
PortCode CarCode PortCode CarCode PortCode CarCode
-----------------------------------------------------------
AAB A5 ADR BH SAN QQ
尝试过PIVOT
,但没有帮助。
任何人都可以向我解释一下,如何实现吗?
答案 0 :(得分:1)
如果我理解正确,
select max(case when seqnum = 1 then portcode end) as portcode_1,
max(case when seqnum = 1 then carcode end) as carcode_1,
max(case when seqnum = 2 then portcode end) as portcode_2,
max(case when seqnum = 2 then carcode end) as carcode_2,
max(case when seqnum = 3 then portcode end) as portcode_3,
max(case when seqnum = 3 then carcode end) as carcode_3
from (select t.*, row_number() over (order by (select null)) as seqnum
from t
) t;
注意:
(select null)
。答案 1 :(得分:1)
如果要使其动态化,可以使用以下 sql
查询。
查询
declare @sql as varchar(max);
select @sql = 'select ' + stuff((
select distinct ',max(case [PortCode] when ' + char(39) + [PortCode] + char(39) +
' then [PortCode] end) as [PortCode]'
+ ',max(case [CarCode] when ' + char(39) + [CarCode] + char(39) +
' then [CarCode] end) as [CarCode]'
from [your_table_name]
for xml path('')
), 1, 1, '');
select @sql += ' from [your_table_name];';
exec(@sql);