我有两个带有列的表:Sales_Margin:分支,项目代码,项目名称,销售数量,销售率,成本,保证金
目录: 垂直,项目ID,零件说明
我需要以这样的方式输出:“目录”表中“垂直”中的不同值是列,而“销售报告”表中的“分支”中是行。 我通过数据透视获得了这一部分:
我的代码:
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
但是我还需要“销售报告”表中“保证金”列的总和,以使保证金按分支分组(将输出复制为excel并采用百分比) 预期输出:
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
我尝试使用相关的子查询,如下所示,但它不起作用:
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
它说,
The multi-part identifier "x.branch" could not be bound.
有人可以让我知道如何获取按分支添加分组数值的保证金列
答案 0 :(得分:0)
您需要使用z.branch
,因为它引用了该外部子查询。