简体   繁体   中英

Pivot a table and combine result with aggregate of a column

I have two tables with columns: Sales_Margin: Branch, Item Code, Item Name, Sale Qty, Sale Rate, Cost, Margin

Catalogue: VERTICAL, ITEM ID, PARTS DESCRIPTION

I need output in such a way that the distinct values in VERTICAL from Catalogue table are columns and Branches from Sales Report table are rows. I got that part using pivot:

My Code:

select branch as Branch, [Vertical1], [Vertical2], [Vertical3], 
[Vertical4]
from 
( 
select branch, vertical, round((sum(margin)/sum([Sale Rate])),3) [Avg GM]
from
Sales_Margin JOIN Catalogue
ON Sales_Margin.[Item Code] = Catalogue.[ITEM ID]
group by branch, VERTICAL
) x
pivot
(
    sum([Avg GM]) 
        for vertical 
    in([Vertical1], [Vertical2], [Vertical3], [Vertical4])
) as pivot_table

But I also need sum of 'Margin' column from Sales Report table such that Margins are grouped by the Branch (Will copy output to excel and take Percentages) Expected Output:

  Branch Vertical1 Vertical2 Vertical3  Vertical4       Margin
       A1       0%       9%       52%         0%       A1 Margin
       A2       40%      9%       66%         1%       A2 Margin    
       A3       32%      4%       57%         2%       A3 Margin    
       A4       17%      9%       65%         17%      A4 Margin    

I tried using a correlated subquery as below but it doesn't work:

select branch as Branch, [Vertical1], [Vertical2], [Vertical3], 
[Vertical4], 
(select sum(Margin) from Sales_Margin a where a.Branch = 
x.branch)
from 
(
select branch as Branch, [Vertical1], [Vertical2], [Vertical3], 
[Vertical4]
from 
( 
select branch, vertical, round((sum(margin)/sum([Sale Rate])),3) [Avg GM]
from
Sales_Margin JOIN Catalogue
ON Sales_Margin.[Item Code] = Catalogue.[ITEM ID]
group by branch, VERTICAL
) x
pivot
(
    sum([Avg GM]) 
    for vertical 
    in([Vertical1], [Vertical2], [Vertical3], [Vertical4])
) as pivot_table
) z

It says,

The multi-part identifier "x.branch" could not be bound.

could someone please let me know how to get the Margin column with numeric values added grouped by branch

您需要使用z.branch ,因为它引用了外部子查询。

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