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

Mysql SQL-子查询错误和求和错误,mysql,sum,subquery,Mysql,Sum,Subquery,我的SQL代码如下所示。我遇到的问题首先是子查询。 结果显示错误: SQL错误:子查询返回的值超过1。这是不允许的 当子查询跟随=,!=,=或者当子查询是 用作表达 需要显示日期大于或等于ESource=Detail所在日期的行-这些行需要在某些列中求和,在其他列中选择单个值 使用的代码: select DISTINCT A.Policy, A.Fund, (SUM(A.AddUnits)) AS SUM, ((C.TotalUnits - (SUM(A.AddUnits)))

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

SQL错误:子查询返回的值超过1。这是不允许的 当子查询跟随=,!=,=或者当子查询是 用作表达

需要显示日期大于或等于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
表格如下:

表A:

保单基金单位价格来源日期

120 BR 6 0.74 RE 2015

120 BR-100 0.72详图2014

120 BR 6 0.71 RE 2013

表C:

政策基金总额单位

120溴400

预期结果:

政策基金总额价格价值

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

与子查询问题一样,获取price=0.72[where=Detail]的命令将停止两行的总和,使总和为-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 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子句中

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')