Question : cross tab sql query

Hi  Experts

is there any simple query to make a cross tab?

my data looks like this:

id     name
1      gidi1
1      gidi2
1      gidi3
2      gidi4
2      gidi5

and i want it to look like that:

id          name1   name2    name3
1           gidi1      gidi2       gidi3
2           gidi4      gidi5

10x a lot

Answer : cross tab sql query

try like this.

select id,
       max(case rn when 1 then name end) as name1,
       max(case rn when 2 then name end) as name2,
       max(case rn when 3 then name end) as name3
  from (select *,row_number() over (partition by id order by name) as rn
          from your_table) as t1
 group by id
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
declare @table as table(id int,name varchar(10))
insert into @table values(1,      'gidi1')
insert into @table values(1 ,     'gidi2')
insert into @table values(1  ,    'gidi3')
insert into @table values(2   ,   'gidi4')
insert into @table values(2    ,  'gidi5')

select id,
       max(case rn when 1 then name end) as name1,
       max(case rn when 2 then name end) as name2,
       max(case rn when 3 then name end) as name3
  from (select *,row_number() over (partition by id order by name) as rn 
          from @table) as t1
 group by id
/*
1	gidi1	gidi2	gidi3
2	gidi4	gidi5	NULL
*/
Random Solutions  
 
programming4us programming4us