[英]SQL - Subquery Error and Sum Error
我的SQL代码如下所示。 我遇到的问题首先是子查询。 结果显示错误:
SQL错误:子查询返回了多个值。 当子查询遵循=,!=,<,<=,>,> =或将子查询用作表达式时,不允许这样做
需要显示日期大于(或等于)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:
保单基金单位价格ESource日期
120 BR 6 0.74 RE 2015年
120 BR -100 0.72细节2014
120 BR 6 0.71稀土2013
表C:
保单基金合计
120牛400
所需结果:
政策性基金总价值
120 BR [6 +(-100)] = -94 0.72 [(400 +(-94))* 0.72] = 220.32
以及子查询问题-获取price = 0.72 [where ="Detail"]
的命令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')
最后两个子句是问题所在。 解决此问题的一种方法是使用关键字ANY
, SOME
或ALL
:
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
子句中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.