有一批记录,想将负数自动按照正数项目所含正数的比例分摊,如下:
细类 金额
A 400
B -100
C -200
D 500
总正数:900 总负数:-300
组合成:
A 400+4/9*(-300)
B 500+5/9*(-300)
请问各位大侠,sql有头绪吗?
------解决方案--------------------
- SQL code
这个?SELECT NAME,NUM+NUM/(SELECT SUM(NUM) FROM ABC where NUM>0)*(SELECT SUM(NUM) FROM ABC where NUM<0) FROM ABC
------解决方案--------------------
------解决方案--------------------
- SQL code
--> 测试数据:[tb]IF OBJECT_ID('[tb]') IS NOT NULL DROP TABLE [tb]GO CREATE TABLE [tb]([细类] VARCHAR(1),[金额] INT)INSERT [tb]SELECT 'A',400 UNION ALLSELECT 'B',-100 UNION ALLSELECT 'C',-200 UNION ALLSELECT 'D',500--------------开始查询--------------------------SELECT [细类],[金额]+[金额]*1.0/(SELECT SUM([金额]) FROM [tb] WHERE [金额]>0)*(SELECT SUM([金额]) FROM [tb] WHERE [金额]<0) FROM [tb] WHERE [金额]>0----------------结果----------------------------/* 细类 (无列名)A 266.666666666800D 333.333333333500*/