简体   繁体   中英

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!

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

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM