Zane Key Zane Key - 4 months ago 16
SQL Question

Create a table from another table in sql server 2005

I have already a table like this:

enter image description here

I want to create another table, get data from above table and the result like this:

enter image description here

How can I do it? Thanks for any help.

Answer

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
Comments