sql server - How to pivoting -
i don't understanding pivoting , need on simple query using union
. query gives me results fellows:
select 'luft' [source], sum([salesamount1]) [sales old], sum([salesamount2]) [sales new] [dbo].[tblsales] ([source] in ('luft')) , [planung] = 'kosten' union select 'tgl' [source], sum([salesamount1]) [sales old], sum([salesamount2]) [sales new] [dbo].[tblsales] ([source] in ('tgl')) , [planung] = 'kosten' union select 'bhw' [source], sum([salesamount1]) [sales old], sum([salesamount2]) [sales new] [dbo].[tblsales] ([source] in ('bhw')) , [planung] = 'kosten' union select 'wm ' [source], sum([salesamount1]) [sales old], sum([salesamount2]) [sales new] [dbo].[tblsales] ([source] in ('wm')) , [planung] = 'kosten'
results:
[source] [sales old] [sales new] luft 10000 20000 tgl 500 800 bhw 1500 500 wm 700 400
my expectation using pivot:
[] [luft] [tgl] [bhw] [wm] sales old 10000 500 1500 700 sales new 20000 800 500 400
your use of union
appends 2 select statements together. reason results how are, you're selecting source , old/new sales columns.
for desired output write below:
if have questions method or query feel free ask.
select 'sales old' [category], sum(case when [source] = 'luft' [salesamount1] else 0 end) [luft], sum(case when [source] = 'tgl' [salesamount1] else 0 end) [tgl], sum(case when [source] = 'bhw' [salesamount1] else 0 end) [bhw], sum(case when [source] = 'wm' [salesamount1] else 0 end) [wm] [dbo].[tblsales] [planung] = 'kosten' union select 'sales new' [category], sum(case when [source] = 'luft' [salesamount2] else 0 end) [luft], sum(case when [source] = 'tgl' [salesamount2] else 0 end) [tgl], sum(case when [source] = 'bhw' [salesamount2] else 0 end) [bhw], sum(case when [source] = 'wm' [salesamount2] else 0 end) [wm] [dbo].[tblsales] [planung] = 'kosten'
Comments
Post a Comment