我的SQL代码如下所示。我遇到的问题是计算每个数字的值的总和。单独执行它们是正常的,并且在代码中指定了数字时有效,但是当未指定数字时则无效,并且我希望总和计算适用于所有单独的数字。
{看起来计算税收点的价值。因此,税务日期之前的所有值都将被忽略,并且税后日期之后发生的所有单位条目将从总单位中减去。税单位也被减去。每个基金的税收总单位乘以税点的价格。将资金的值相加,得出该数字的总值。 }
这是我所做的代码:
SELECT DISTINCT
A.Number,
CAST(ROUND((SELECT SUM(Val)
FROM (SELECT((S.TotalUnits -
(SELECT SUM(Units)
FROM TableIH AS F WHERE F.Fund = S.Fund AND F.Number = S.Number
AND F.Date >= (SELECT MIN(Date) FROM TableIH AS D
WHERE D.Fund= F.Fund AND D.Number = F.Number AND D.Entry = 'Tax' )
)
) * T.Price
) AS Val
FROM TableIH T
INNER JOIN TableID S
ON T.Number = S.Number
WHERE S.TotalUnits > 0 AND T.Fund = S.Fund
AND T.Price = ANY (SELECT (Price)
FROM TableIH AS E WHERE E.Entry = 'Tax' AND E.Number = T.Number)
)t
)
,2)
AS DECIMAL (25,2)) AS "Value"
FROM
TableIH A
INNER JOIN TableID C
ON C.Number = A.Number
group by A.Number
表格是:
TableIH:
数字基金进入单位价格日期
12 YY RE 6 0.2 2015-02-02
12 YY Tax -10 0.1 2015-01-13
13 XX RE 6 0.2 2015-02-12
13 XX Tax -20 0.05 2014-12-11
13 MM Tax -25 0.6 2014-12-10
13 MM RE 8 0.2 2013-11-02
表格ID
Number Fund TotalUnits
2000 YY 2000
13 XX 1500
13 MM 500
期望的结果:
数值
12 [((2000) - (6) - (-10))* 0.1] = 200.4
13 [((1500) - (6) - (-20))* 0.05] + [((500) - (-25))* 0.6] = 390.7
但是获得: - 结果是对所有数字进行求和,而不是在每个数字之间进行除法。
数值
12 [(200.4 + 390.7)= 591.1
13 [(200.4 + 390.7)= 591.1
非常感谢任何有关错误的帮助
答案 0 :(得分:0)
晚上好,问题在于你的第三个嵌套子查询,你的总和上没有任何组,所以它总结所有单位,所以你只得到一个:
SELECT SUM(Units)
FROM TableIH AS F WHERE F.Fund = S.Fund AND F.Number = S.Number
AND F.Date >= (SELECT MIN(Date) FROM TableIH AS D
WHERE D.Fund= F.Fund AND D.Number = F.Number AND D.Entry = 'Tax'