我的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:
政策基金TotalUnits
120 BR 400
期望的结果:
政策基金总和价值
120 BR [6 +( - 100)] = -94 0.72 [(400 +( - 94))* 0.72] = 220.32
除了子查询问题之外 - 获取price = 0.72 [where ="Detail"]
的命令正在停止发生Sum = -100
而不是-94
非常感谢任何有关错误的帮助
答案 0 :(得分:0)
问题出在你的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
子句中。