【问题标题】:Splitting data from one column into multiple rows in SQL Server在 SQL Server 中将数据从一列拆分为多行
【发布时间】:2021-03-08 16:40:57
【问题描述】:

我是 SQL 的初学者,很遗憾我无法解决问题。我有一个系统表中的列名列表,我想根据列名的序列将其插入到表的单独行中。

原表:

Column name
001000
001100
001200
002000
002100
002200
002300

目标表:

Column 1 Column 2 Column 3 Column 4
001000 001100 001200 NULL
002000 002100 002200 002300
...... ...... ...... ......
022000 022100 022200 022300

原始表中有大量行,因此将这些数字分组是非常具有挑战性的。我已经研究过 PIVOT 功能,但这并没有解决这个问题。

不幸的是,由于我是初学者,我也无法将其放入代码中。任何关于推荐我应该研究哪些函数以便我可以开始编写一些代码的帮助都会非常有帮助。任何指向解决方案的指针也非常感谢。

【问题讨论】:

    标签: sql sql-server pivot


    【解决方案1】:

    条件聚合应该做你想做的事:

    select max(case when seqnum = 1 then column end),
           max(case when seqnum = 2 then column end),
           max(case when seqnum = 3 then column end),
           max(case when seqnum = 4 then column end)
    from (select t.*,
                 row_number() over (partition by left(column, 3) order by column) as seqnum
          from t
         ) t
    group by left(column, 3)
    

    【讨论】:

      猜你喜欢
      • 2018-08-30
      • 1970-01-01
      • 2022-06-15
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 2016-04-10
      • 2019-11-03
      • 1970-01-01
      相关资源
      最近更新 更多