Search code examples
sqlsql-servert-sqlpivotunpivot

SQL Pivot select multiple rows


This is the table I have:

Tasble for pivot looks like this

I want to create pivot like this: enter image description here

I've wrote some query, but I get only names diagonally:

(
select 
[1] as Client0, 
[2] as Client1, 
[3] as Client2, 
[4] as Client3,
[5] as Client4
from 
(
select 
    rc.DateCreated, 
    gd.Name,
    DENSE_RANK() over (order by gd.ID_TableGD) as colnum
from TableGD gd
inner join TableRC rc ON gd.ID_TableGD = rc.ID_TableRC
WHERE gd.ID_TableGD IN (962,1029,1024) 
AND gd.Active = 1
) as t
pivot
(
MAX(Name)
for colnum in 
(
[1],
[2],
[3],
[4],
[5]

)
) as pvt) 

So, I want to be able for particular client to get clientName (ClientA) and CreatedDate in same column.

This is my first pivot, and I am not sure if I need to put Max(Name)?

And I get table like this: enter image description here


Solution

  • Use max in time of selection like below:

    select 
    max([1]) as Client0, 
    max([2]) as Client1, 
    max([3]) as Client2, 
    max([4]) as Client3,
    max([5]) as Client4
    from 
    (
    select 
        rc.DateCreated, 
        gd.Name,
        DENSE_RANK() over (order by gd.ID_TableGD) as colnum
    from TableGD gd
    inner join TableRC rc ON gd.ID_TableGD = rc.ID_TableRC
    WHERE gd.ID_TableGD IN (962,1029,1024) 
    AND gd.Active = 1
    ) as t
    pivot
    (
    MAX(Name)
    for colnum in 
    (
    [1],
    [2],
    [3],
    [4],
    [5]
    
    )
    ) as pvt