我已经在这个问题上花了好头两天了。
这是我的问题:
我有18个水桶。一个桶具有负值。我需要在其他17个桶中分配负值,占17个桶总数的百分比。我可以在Excel中执行此操作,但我需要在没有任何硬编码的情况下在T-SQL中执行此操作,因为这将在存储过程中使用。这是我的数据(Bucket and Amount)和Excel的结果(总计,分配和新金额的百分比):
BUCKET AMOUNT [Pct of Total] Distribution [New Amount]
1 $174,130.91 9.5384% $(281.49) $173,849.41
2 $54,274.13 2.9730% $(87.74) $54,186.39
3 $150,637.86 8.2515% $(243.51) $150,394.34
4 $389,910.65 21.3581% $(630.31) $389,280.34
5 $379,177.75 20.7702% $(612.96) $378,564.79
6 $79,230.40 4.3400% $(128.08) $79,102.32
7 $47,008.64 2.5750% $(75.99) $46,932.64
8 $47,224.95 2.5868% $(76.34) $47,148.60
9 $102,731.42 5.6273% $(166.07) $102,565.35
10 $8,955.93 0.4906% $(14.48) $8,941.45
11 $43,749.52 2.3965% $(70.72) $43,678.80
12 $16,140.85 0.8841% $(26.09) $16,114.76
13 $72,165.14 3.9530% $(116.66) $72,048.48
14 $23,542.26 1.2896% $(38.06) $23,504.21
15 $874.82 0.0479% $(1.41) $873.41
16 $65,665.10 3.5969% $(106.15) $65,558.95
17 $170,162.38 9.3210% $(275.08) $169,887.30
18 $(2,951.15)
Total $1,822,631.55 100.0000% $(2,951.15) $1,822,631.55
答案 0 :(得分:1)
以下是一个如何管理此问题的示例:
;with neg as(select sum(amount) as amount from t where amount < 0),
pos as(select * from t where amount >= 0)
select *,
p.amount * 100 / sum(p.amount) over() as pct,
neg.amount * p.amount / sum(p.amount) over() as dist,
p.amount + neg.amount * p.amount / sum(p.amount) over() as new
from pos p
cross join neg