How to make pivot table in SQL Server in my case? -
i wants display record same column. don't know how describe question also.
i have table called soldqtytable
itemno weeks years qtysold asofweekonhand ---------------------------------------------------- 1 1 2017 5 3 2 1 2017 2 5 3 1 2017 66 70 1 2 2017 4 33
i wants display below
itemno years [1qtysold] [1_onhand] [2qtysold] [2_onhand] ----------------------------------------------------------------------- 1 2017 5 3 4 33 2 2017 2 5 3 2017 66 70
i tried in way. doesn't work
select pvt1.itemid, pvt1.storeid, pvt1.years, isnull([1],0) [1qtysold], isnull([2],0) [2qtysold], isnull([1_onhand],0) [1_onhand], isnull([2_onhand],0) [2_onhand] ( select itemid, storeid, years, weeks, asofweekonhand soldqtytable ) l pivot ( sum(asofweekonhand) weeks in ( [1_onhand], [2_onhand]) ) pvt1 left join ( select itemid, storeid, years, weeks, qtysold soldqtytable ) l pivot ( sum(qtysold) weeks in ( [1soldqty], [2soldqty] ) pvt2 on pvt2.itemid = pvt1.itemid , pvt1.years = pvt2.years pvt1.years = 2017
i find conditional aggregation simpler:
select itemid, years, sum(case when weeks = 1 qtysold end) qtysold_1, sum(case when weeks = 1 asofweekonhand end) asofweekonhand_1, sum(case when weeks = 2 qtysold end) qtysold_2, sum(case when weeks = 3 asofweekonhand end) asofweekonhand_2 soldqtytable group itemid, years order itemid, years;
Comments
Post a Comment