我写了一个视图,分摊不同销售部门的成本,我想知道是否有更好的方法来做到这一点。
让我们说我有一些输出这个的代码......
Dept Type Oct Nov Dec
DeptA SalesA 10000 20000 5000
DeptA SalesB 4000 2000 8200
DeptA SalesC 6000 7000 4000
DeptB SalesA 12000 4000 6333
DeptB SalesB 8445 3880 4500
DeptB SalesC 8700 8740 6500
General Costs1 890 5874 138
General Costs2 545 547 320
General Costs3 2674 354 214
我希望分摊费用1'跨越销售部门并报告' SalesB'来自' DeptA就像这样......
Oct Nov Dec
SalesB 4000.00 2000.00 8200.00
Approtioned cost1 152.94 499.59 17.98
..(其中'分摊成本1' =成本1 *(DeptA.SalesB /总销售额))。
到目前为止我写的代码看起来像这样......
select
Dept,
Type,
[Oct-15],
[Nov-15],
[Dec-15]
from ProfitandLoss
where Type like 'SalesB%'
and Dept like 'DeptA'
union
select
'Apportioned Costs1' as 'Dept',
'' as 'Type',
round(((round((select sum([Oct-15]) from ProfitandLoss where Type = 'Costs1'),2))* (round((select sum([Oct-15]) from ProfitandLoss where Type like 'SalesB%' and Dept like 'DeptA'),2) / round((select sum([Oct-15]) from ProfitandLoss where type like 'Sales%'),2))),2) as 'Oct-15',
round(((round((select sum([Nov-15]) from ProfitandLoss where Type = 'Costs1'),2))* (round((select sum([Nov-15]) from ProfitandLoss where Type like 'SalesB%' and Dept like 'DeptA'),2) / round((select sum([Nov-15]) from ProfitandLoss where type like 'Sales%'),2))),2) as 'Nov-15',
round(((round((select sum([Dec-15]) from ProfitandLoss where Type = 'Costs1'),2))* (round((select sum([Dec-15]) from ProfitandLoss where Type like 'SalesB%' and Dept like 'DeptA'),2) / round((select sum([Dec-15]) from ProfitandLoss where type like 'Sales%'),2))),2) as 'Dec-15'
from ProfitandLoss
由于查询中的Select语句数量,目前需要43秒才能运行 - 目前这只是一个部门超过三个月。我需要在12个月内为34个部门运行这个! - 有更有效的方法吗? ..是否会存储一个函数,用于存储我可以在查询中引用的每个部门的总销售额百分比,而不是多次进行子查询以获得更快的个别数字?
...还假设成本没有均匀分摊......例如'成本2'只在DeptA.SalesA和DeptB.SalesA之间分开....我需要做出具体的分配而不是一切都除以总数。