试图将SQL Server中的行转换为多列,如下所示:
当前结果:
PortCode CarCode
------------------------
AAB A5
ADR BH
SAN QQ预期结果:
PortCode CarCode PortCode CarCode PortCode CarCode
-----------------------------------------------------------
AAB A5 ADR BH SAN QQ曾尝试过与PIVOT,但没有帮助。
谁能给我解释一下,怎么实现呢?
发布于 2018-09-26 10:36:19
如果我没听错,
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)。发布于 2018-09-26 10:48:08
如果要使其动态,可以使用以下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);https://stackoverflow.com/questions/52515697
复制相似问题