简体   繁体   English

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

[英]Create a table from another table in SQL Server 2005

I have a table like this: 我有一张这样的桌子:

在此处输入图片说明

I want to create another table, get data from above table and have the result be like this: 我想创建另一个表,从上面的表中获取数据,结果是这样的:

在此处输入图片说明

How can I do it? 我该怎么做? Thanks for any help. 谢谢你的帮助。

Considering you have an identity or any other column to identify the order 考虑到您具有标识或其他任何可以识别订单的列

Sample data 样本数据

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)

Query : 查询:

;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

Result: 结果:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM