在SQLServer中将一列中的数据拆分为多行
我是 SQL 的初学者,不幸的是我无法解决问题。我有一个系统表中的列名列表,我想根据列名的序列将其插入到表的单独行中。
原表:
| 列名 |
|---|
| 001000 |
| 001100 |
| 001200 |
| 002000 |
| 002100 |
| 002200 |
| 002300 |
回答
条件聚合应该做你想要的:
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)