【问题标题】:Convert all Rows to Columns in SQL Server在 SQL Server 中将所有行转换为列
【发布时间】:2018-09-26 10:34:04
【问题描述】:

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

当前结果:

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

预期结果:

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

尝试使用PIVOT,但没有帮助。

谁能解释一下,如何实现?

【问题讨论】:

  • 显示您用于数据透视的代码。

标签: sql sql-server pivot pivot-table


【解决方案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) 替换为相应的列。

【讨论】:

    【解决方案2】:

    如果您想使其动态化,可以使用以下 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);
    

    【讨论】:

    • 只需要静态列,你能给我同样的静态列查询吗?
    • @SantoshJadi:抱歉,我没听懂你在问什么。
    • 我正在寻找静态查询。
    猜你喜欢
    • 2013-10-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    • 2021-02-24
    • 2010-10-22
    • 2013-02-12
    相关资源
    最近更新 更多