将列拆分为3列?

时间:2016-07-17 16:39:16

标签: sql sql-server tsql sql-server-2005

我有这样的表1:

----------------
|  id  |  col  |
----------------
|   1  |   7   |
|   2  |   6   |
|   3  |   1   |
|   4  |   8   |
|   5  |   9   |
|   6  |   5   |
|   7  |   4   |
|   8  |   3   |
|   9  |   2   |
----------------

我想从表1的列col创建新表获取数据,并得到如下结果:

-------------------
|  A  |  B  |  C  |
-------------------
|  7  |  6  |  1  |
|  8  |  9  |  5  |
|  4  |  3  |  2  |
-------------------

有什么建议吗?非常感谢。

1 个答案:

答案 0 :(得分:3)

  

假设ID是增量

export class App {
    name = 'WebShop Angular2 App';
    url = '';
    isClassVisible: boolean = false;

    constructor(public appState: AppState) {

    }
}

返回

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)