SQL - 子查询错误和求和错误

SQL - Subquery Error and Sum Error

我的SQL代码如下所示。我遇到的问题首先是子查询。 结果显示错误:

SQL ERROR: Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression

需要显示日期大于(或等于)ESource = Detail 的日期的行 - 这些行需要在某些列中求和,并在其他列中选择单个值。

使用的代码:

select DISTINCT 
  A.Policy, 
  A.Fund, 
 (SUM(A.AddUnits)) AS SUM,
 ((C.TotalUnits - (SUM(A.AddUnits))) * A.Price) AS Value, 

Inner JOIN TableC C
ON C.PolicyNumber = A.PolicyNumber 

where A.PolicyNumber = '120' AND C.NumberOfUnits > 0 AND C.InvestmentFund = A.InvestmentFund 

AND A.DateOfEntry < DATEADD(year, -1, GetDate())
AND A.DateOfEntry >= (Select DateOfEntry FROM TableA AS D where D.ESource = 'Detail') 
AND A.UnitPrice = (Select UnitPrice FROM TableA AS E where E.ESource = 'Detail')

ORDER BY IH.DateOfEntry DESC

Table是:

Table答:

政策 基金 单位 价格 电子来源 日期

120 BR 6 0.74 RE 2015

120 BR -100 0.72 详细信息 2014

120 BR 6 0.71 RE 2013

TABLE C:

保单基金总单位

120 BR 400

期望的结果:

保单 基金 总额 价格 价值

120 BR [6+(-100)] = -94 0.72 [(400+(-94))*0.72] = 220.32

以及子查询问题 - 获取 price = 0.72 [where ="Detail"] 的命令正在停止发生 Sum = -100 而不是 -94

的两行的总和

如有任何错误帮助,我们将不胜感激

问题出在您的 where 子句中:

where A.PolicyNumber = '120' AND
      C.NumberOfUnits > 0 AND
      C.InvestmentFund = A.InvestmentFund  AND
      A.DateOfEntry < DATEADD(year, -1, GetDate()) AND
      A.DateOfEntry >= (Select DateOfEntry FROM TableA AS D where D.ESource = 'Detail') AND
      A.UnitPrice = (Select UnitPrice FROM TableA AS E where E.ESource = 'Detail')

最后两个子句是问题所在。解决此问题的一种方法是使用关键字 ANYSOMEALL:

where A.PolicyNumber = '120' AND
      C.NumberOfUnits > 0 AND
      C.InvestmentFund = A.InvestmentFund  AND
      A.DateOfEntry < DATEADD(year, -1, GetDate()) AND
      A.DateOfEntry >= ALL (Select DateOfEntry FROM TableA AS D where D.ESource = 'Detail') AND
      A.UnitPrice = ALL (Select UnitPrice FROM TableA AS E where E.ESource = 'Detail')

不过,我更喜欢显式聚合:

where A.PolicyNumber = '120' AND
      C.NumberOfUnits > 0 AND
      C.InvestmentFund = A.InvestmentFund  AND
      A.DateOfEntry < DATEADD(year, -1, GetDate()) AND
      A.DateOfEntry >= (Select MAX(DateOfEntry) FROM TableA AS D where D.ESource = 'Detail') AND
      A.UnitPrice = (Select MAX(UnitPrice) FROM TableA AS E where E.ESource = 'Detail')

请注意,您问题中的查询似乎缺少 from 子句。条件 C.InvestmentFund = A.InvestmentFun 应该在 on 子句中,而不是在 where 子句中。