Convert Rows into Columns with Columns Grouping in SQL Server

时间:2016-07-11 20:51:11

标签: sql sql-server sql-server-2008 sql-server-2012 sql-server-2008-r2

I want to implement following below, but don't know where to start:

I have the following output from SQL query:

LocationID     ItemID     ItemName     Price1     Price2 
---------------------------------------------------------
1               101        A             100         150 
1               102        B             220         170 
2               103        C             120         155 
2               104        D             123         160 
3               105        E             158         179 
3               106        F             160         180 

Now I want to make my output to look like this:

                           LocationID 1           LocationID 2
ItemID     ItemName     Price1     Price2     Price1     Price2 
---------------------------------------------------------
101        A             100         150      0           0 
102        B             220         170      0           0 
103        C             0           0        120         155 
104        D             0           0        123         160
105        E             0           0        0           0
106        F             0           0        0           0

How can I do the same in SQL, appreciate if someone can guide me.

P.S ItemID & ItemName are coming from one master table joined with LocationID.

1 个答案:

答案 0 :(得分:0)

Like I said...conditional aggregation.

if OBJECT_ID('tempdb..#Something') is not null
    drop table #Something

CREATE TABLE #Something
(
    LocationID int
    , ItemID int
    , ItemName char(1)
    , Price1 int
    , Price2 int
)

insert #Something
select 1, 101, 'A', 100, 150 union all
select 1, 102, 'B', 220, 170 union all
select 2, 103, 'C', 120, 155 union all
select 2, 104, 'D', 123, 160 union all
select 3, 105, 'E', 158, 179 union all
select 3, 106, 'F', 160, 180;

select LocationID
    , ItemName
    , Location1_Price1 = MAX(case when LocationID = 1 then Price1 else 0 end)
    , Location1_Price2 = MAX(case when LocationID = 1 then Price2 else 0 end)
    , Location2_Price1 = MAX(case when LocationID = 2 then Price1 else 0 end)
    , Location2_Price2 = MAX(case when LocationID = 2 then Price2 else 0 end)
from #Something
group by LocationID
    , ItemName