从SQL Server 2005中的另一个表创建一个表

时间:2016-07-03 04:28:16

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

我有一张这样的表:

enter image description here

我想创建另一个表,从上面的表中获取数据,结果如下:

enter image description here

我该怎么办?谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

考虑到您有一个身份或任何其他列来识别订单

示例数据

create table test_tab
(id int identity(1,1), sophong int)
insert into test_tab values (7)
insert into test_tab values (4)
insert into test_tab values (11)
insert into test_tab values (7)
insert into test_tab values (4)
insert into test_tab values (11)
insert into test_tab values (6)
insert into test_tab values (3)
insert into test_tab values (11)

查询:

;WITH cte as
(
SELECT *,((ROW_NUMBER() over(order by id)-1)/3)+1 as iden,
         ((ROW_NUMBER() over(order by id)-1)%3)+1 as ident  
FROM test_tab
)
SELECT max(case when iden = 1 then sophong end) as [1],
       max(case when iden =2 then sophong end) as [2],
       max(case when iden = 3 then sophong end) as [3]

FROM cte
group by ident

<强>结果:

1   |2  |3
----+---+---
7   |7  |6
4   |4  |3
11  |11 |11