在SQL Server中将行转换为多列

时间:2018-09-26 10:34:04

标签: sql sql-server

尝试在SQL Server中将行转换为多列,如下所示:

当前结果:

PortCode    CarCode
------------------------
AAB         A5
ADR         BH
SAN         QQ

预期结果:

PortCode    CarCode   PortCode  CarCode   PortCode  CarCode
-----------------------------------------------------------
AAB         A5        ADR       BH        SAN       QQ

尝试过PIVOT,但没有帮助。

任何人都可以向我解释一下,如何实现吗?

2 个答案:

答案 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;

注意:

  • 这不是动态的。它产生6列(但您可以对动态查询使用相同的想法)。
  • 结果的顺序不确定。 SQL表表示无序集。如果要按特定顺序排列列,请用适当的列替换(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);