将一列拆分为 3 列?
Split a column into 3 columns?
我有 table 1 个这样的:
----------------
| id | col |
----------------
| 1 | 7 |
| 2 | 6 |
| 3 | 1 |
| 4 | 8 |
| 5 | 9 |
| 6 | 5 |
| 7 | 4 |
| 8 | 3 |
| 9 | 2 |
----------------
我想创建新的 table 从 table 1 的 col
列获取数据并得到如下结果:
-------------------
| A | B | C |
-------------------
| 7 | 6 | 1 |
| 8 | 9 | 5 |
| 4 | 3 | 2 |
-------------------
有什么建议吗?非常感谢。
Assuming the ID is incremental
Declare @Table table (id int,col int)
Insert Into @Table values
(1,7),
(2,6),
(3,1),
(4,8),
(5,9),
(6,5),
(7,4),
(8,3),
(9,2)
Select ColA=max(case when ID % 3 = 1 then col else 0 end)
,ColB=max(case when ID % 3 = 2 then col else 0 end)
,ColC=max(case when ID % 3 = 0 then col else 0 end)
From @Table
Group By ceiling(ID/3.0)
Returns
ColA ColB ColC
7 6 1
8 9 5
4 3 2
我有 table 1 个这样的:
----------------
| id | col |
----------------
| 1 | 7 |
| 2 | 6 |
| 3 | 1 |
| 4 | 8 |
| 5 | 9 |
| 6 | 5 |
| 7 | 4 |
| 8 | 3 |
| 9 | 2 |
----------------
我想创建新的 table 从 table 1 的 col
列获取数据并得到如下结果:
-------------------
| A | B | C |
-------------------
| 7 | 6 | 1 |
| 8 | 9 | 5 |
| 4 | 3 | 2 |
-------------------
有什么建议吗?非常感谢。
Assuming the ID is incremental
Declare @Table table (id int,col int)
Insert Into @Table values
(1,7),
(2,6),
(3,1),
(4,8),
(5,9),
(6,5),
(7,4),
(8,3),
(9,2)
Select ColA=max(case when ID % 3 = 1 then col else 0 end)
,ColB=max(case when ID % 3 = 2 then col else 0 end)
,ColC=max(case when ID % 3 = 0 then col else 0 end)
From @Table
Group By ceiling(ID/3.0)
Returns
ColA ColB ColC
7 6 1
8 9 5
4 3 2