Abhishek_Chourasia
Abhishek_Chourasia

Reputation: 109

Pivot in SQL Server with where clause

I am in need for using Pivot in SQL for getting the rows converted in columns, but not able to do so with my pivot query.

    create table TestTable
    (
      id int,
      colVal int
    )

insert into TestTable values(1,1)
insert into TestTable values(1,2)
insert into TestTable values(1,4)
insert into TestTable values(2,1)
insert into TestTable values(2,2)
insert into TestTable values(2,6)

I am trying to get the values of colVal in the columns based on the below query where clause.

select * from
(
    Select ID,colVal
    from TestTable
    where ID=1
) as PV
pivot
(max(id) for colVal in([1], [2], [3])) piv

For every ID there can only be 3 colValues hence I have specified [1],[2],[3] in the pivot.

I am looking for output like
ID  c1 c2 c3
1   1  2  4

Can anyone help me out here.

Upvotes: 3

Views: 5801

Answers (1)

John Cappelletti
John Cappelletti

Reputation: 81970

Just use Row_Number() to create the column sequence

select id,[1] as c1,[2] as c2,[3] as c3 from
(
    Select ID
          ,col    = row_number() over (Partition By ID Order by colVal)
          ,colVal
    from TestTable
    where ID=1
) as PV
pivot
(max(colVal) for col in([1], [2], [3])) piv

Returns

ID  c1  c2  c3
1   1   2   4

EDIT - Dynamic Version

Declare @SQL varchar(max) = Stuff((Select Distinct ',' + QuoteName(concat('C',row_number() over (Partition By ID Order by colVal))) 
                                    From  TestTable  
                                    Order By 1 
                                    For XML Path('')
                                  ),1,1,'') 
Select  @SQL = '
Select [id],' + @SQL + '
From (
        Select ID
              ,col    = concat(''C'',row_number() over (Partition By ID Order by colVal))
              ,colVal
        from TestTable
        where ID=1
     ) A
 Pivot (max(colVal) For [col] in (' + @SQL + ') ) p'
Exec(@SQL);

EDIT for 2008

Declare @SQL varchar(max) = Stuff((Select Distinct ',' + QuoteName('C'+cast(row_number() over (Partition By ID Order by colVal) as varchar(10))) 
                                    From  TestTable  
                                    Order By 1 
                                    For XML Path('')
                                  ),1,1,'') 
Select  @SQL = '
Select [id],' + @SQL + '
From (
        Select ID
              ,col    = ''C''+cast(row_number() over (Partition By ID Order by colVal) as varchar(10))
              ,colVal
        from TestTable
        where ID=1
     ) A
 Pivot (max(colVal) For [col] in (' + @SQL + ') ) p'
Exec(@SQL);

Upvotes: 6

Related Questions