Jiah
Jiah

Reputation: 93

Pivoting rows to columns

Below is my raw data: raw data

I want the data to be pivoted as below : pivoted data

select cvid, cid,67554,67555,67556,67557 
from #temp2 pivot
    (
    max(lcd)
    for qid in ([67554],[67555],[67556],[67557])
    )as P

This is the code I tried. Need help!

Upvotes: 3

Views: 1549

Answers (3)

codeballer
codeballer

Reputation: 21

If you are using Oracle SQL, try

select * from (
    select cvid, cid, qid, lcd
    from #temp2
) a
pivot
(
    max(lcd)
    for qid in (67554,67555,67556,67557)
) b
order by cvid;

Upvotes: 2

Pat Jones
Pat Jones

Reputation: 896

Here is a possibility, using fairly generic syntax:

select CVID, CID, sum(case when QID = 67554 then LCD else 0 end) as [67554],
                  sum(case when QID = 67555 then LCD else 0 end) as [67555],
                  sum(case when QID = 67556 then LCD else 0 end) as [67556],
                  sum(case when QID = 67557 then LCD else 0 end) as [67557] 
from test1
group by CVID, CID;

I tested this in SSMS for SQL Server 2012.

Upvotes: 2

Andrew
Andrew

Reputation: 373

Two things: Make sure you have a source table to pivot. The source table will include the columns you wish to aggregate. In this case, I have given it the alias 'src'. Second, when you are using numbers as column names, make sure to use brackets. Alternatively, begin the column name with a letter. Example, [67554] as Col_67554. I provided that example in the code.

select cvid, cid,[67554] as Col_67554,[67555],[67556],[67557] 
    from 
    (select cvid, cid, lcd, qid from #temp2) as src
    pivot
    (
    max(lcd) for qid in ([67554],[67555],[67556],[67557])
    ) p

Upvotes: 2

Related Questions