我有以下代码不断抛出此错误:
子查询返回了多个值。当子查询遵循=,!=,<,<=,>,> =或将子查询用作表达式时,不允许这样做。
代码:
SELECT (SELECT SumOfAmount
FROM (SELECT SUM(Proposals.Amount) AS SumOfAmount
FROM Proposals
WHERE Proposals.EstCloseDate Between DATEADD(YEAR,-0, GETDATE()) AND DATEADD(MONTH, +12, GETDATE())
GROUP BY Proposals.SalesRep, Proposals.ProposalStatus
HAVING Proposals.ProposalStatus = 3) Proposals
),
(SELECT SumOfEstAmount
FROM (SELECT Sum(Prospects.EstAmount) AS SumOfEstAmount
FROM Prospects
WHERE Prospects.ProspectStatus = 1 AND
Prospects.EstProposalDate BETWEEN DATEADD(YEAR,-0, DATEADD(MONTH, 1, GETDATE())) AND DATEADD(YEAR,+12, DATEADD(MONTH, 0, GETDATE()))
GROUP BY Prospects.SalesRep) Proposals
)
FROM Proposals
INNER JOIN SalesRep ON Proposals.SalesRep = SalesRep.SalesRepID
INNER JOIN Prospects ON Proposals.Amount = Prospects.EstAmount
GROUP BY Prospects.SalesRep, Proposals.SalesRep, Proposals.ProposalStatus,Proposals.Amount
答案 0 :(得分:0)
由于在子选择中使用了GROUP BY,因此在主查询的选择列表中将获得多行。
使用CASE仅对某些值求和,而不是使用子选择。
df["column"].fillna(0, inplace=True)
另外,由于要求和,请勿按df.loc["column"].fillna(0, inplace=True)
分组。也加入SELECT
SUM(CASE WHEN P1.ProposalStatus = 3 AND
P1.EstCloseDate Between DATEADD(YEAR,-0, GETDATE()) AND DATEADD(MONTH, +12, GETDATE())
THEN P1.Amount
ELSE 0
END) AS SumOfAmount,
SUM(CASE WHEN P2.ProspectStatus = 1 AND
P2.EstProposalDate BETWEEN DATEADD(YEAR,-0, DATEADD(MONTH, 1, GETDATE())) AND DATEADD(YEAR,+12, DATEADD(MONTH, 0, GETDATE()))
THEN P2.EstAmount
ELSE 0
END) AS SumOfEstAmount
FROM
Proposals P1
INNER JOIN SalesRep S ON P1.SalesRep = S.SalesRepID
INNER JOIN Prospects P2 ON P1.Amount = P2.EstAmount
GROUP BY P2.SalesRep, P1.SalesRep, P1.ProposalStatus
看起来很奇怪;但是,我不知道您到底想要实现什么。
答案 1 :(得分:-1)
关键答案是“前1名”。如果您使用子查询,则应在其中使用前1个