在具有多个百分比行的“选择不同的”查询中计算总金额中的新百分比

时间:2018-07-17 10:56:40

标签: sql sql-server

标题可能令人困惑,但是对于阅读以下几行的人来说,情况应该真的很简单。

我有这张桌子 VAL

customer month_1 month_2 month_3 value
ABC        0.5     0      0.50    200
ABC       0.25     0.25   0.50    200
XYZ          1     0         0    150
RST          0     0         1    200
RST          0     0.50   0.50    130

(这是获取代码)

create table VAL (customer nvarchar(255), month_1 decimal(18,2), month_2 decimal(18,2), month_3 decimal(18,2), value decimal(18,2))
insert into VAL values ('ABC',  0.5,     0  ,    0.50,    200)
insert into VAL values ('ABC',0.25 ,    0.25,   0.50 ,   200 )
insert into VAL values ('XYZ',   1 ,    0   ,      0 ,   150 )
insert into VAL values ('RST',   0 ,    0   ,      1 ,   200 )
insert into VAL values ('RST',   0 ,    0.50,   0.50 ,   130 )

这可以看到(转换为实际值的百分比)为

customer value_month_1 value_month_2 value_month_3 value
ABC         100              0             100      200
ABC          50             50             100      200
XYZ         150              0               0      150
RST           0              0             200      200
RST           0             65              65      130

我需要转换下表中的所有内容,这是第一个表格的折叠版本:

customer  month_1   month_2  month_3   value
ABC        0.375     0.125     0.50     400
XYZ          1.0         0      0.0     150
RST          0.0     0.197    0.793     330

到目前为止,我可以使用以下代码按客户划分此客户:

select distinct customer
,sum(month_1) as month_1
,sum(month_2) as month_2
,sum(month_3) as month_3
,sum(value) as value
from (
select distinct customer
,month_1 * sum(value)/(select sum(value) from VAL where customer='ABC' group by customer) as month_1
,month_2 * sum(value)/(select sum(value) from VAL where customer='ABC' group by customer) as month_2
,month_3 * sum(value)/(select sum(value) from VAL where customer='ABC' group by customer) as month_3
,sum(value) as value from VAL where customer='ABC' group by customer, month_1, month_2,month_3) as NEW
group by customer

给出以下结果:

customer  month_1   month_2  month_3   value
ABC        0.375     0.125     0.50     400

我很确定有更好的方法来执行此操作,可能是通过一些我不太了解如何使用的命令。 有人能帮忙吗?

1 个答案:

答案 0 :(得分:1)

您只需要加权平均值:

select customer,
       sum(month_1 * value) / sum(value) as month_1,
       sum(month_2 * value) / sum(value) as month_2,
       sum(month_3 * value) / sum(value) as month_3,
       sum(value)
from val
group by customer;