我早上大部分时间都在研究这个查询,使用Stack Overflow并尝试不同的东西。这经历了许多次迭代。我发布了我被卡住的步骤,我知道什么是错的,我似乎无法弄清楚如何修复它。
问题在于:
我需要返回给定日期范围之间捐赠的总金额。我认为在选择中使用SUM会做到这一点,但是当我将条件Amount >= '4000'
添加到WHERE
子句时,它会返回超过4000的所有捐赠的总和,而不是所有捐赠的总和。 TOTAL超过4000.我觉得我需要让它执行子查询,但我不知道在哪里放它。我也可能完全错误,并使用不正确的语法来实现我想要实现的目标。
代码如下。谢谢!
SELECT do.[donorId] as 'ID',
d.[fn] as 'First Name',
d.[ln] as 'Last Name',
SUM(do.[amount]) as Amount
FROM [OURDB].[dbo].[Donation] AS do
JOIN [OURDB].[dbo].[Donor] AS d ON do.[donorId] = d.[donorId]
WHERE do.[donationDate] > '2015-07-01 00:00:00.000' and do.[donationDate] < '2016-07-01 00:00:00.000'
GROUP BY do.[donorId], d.[fn], d.[ln], do.[amount]
答案 0 :(得分:3)
使用Having子句执行此操作:
SELECT do.[donorId] as 'ID',
d.[fn] as 'First Name',
d.[ln] as 'Last Name',
SUM(do.[amount]) as Amount
FROM [OURDB].[dbo].[Donation] AS do
JOIN [OURDB].[dbo].[Donor] AS d ON do.[donorId] = d.[donorId]
WHERE do.[donationDate] > '2015-07-01 00:00:00.000' and do.[donationDate] < '2016-07-01 00:00:00.000'
GROUP BY do.[donorId], d.[fn], d.[ln]
Having SUM(do.amount) > 4000