在WHERE子句中获取sum()

时间:2015-04-20 08:48:43

标签: sql sql-server-2008

我有这个SQL,但它无法正常工作。

SELECT     [Customer No_], SUM(Amount) AS SumDebitor, [Posting Date]
FROM         dbo.[3S Company A_S$Detailed Cust_ Ledg_ Entry]
WHERE     ([Posting Date] <= CONVERT(DATETIME, '2015-04-10 00:00:00', 102))
GROUP BY [Customer No_], [Posting Date]
HAVING      ([Customer No_] = '45')

我想要的是从我的约会之前获得所有帖子的总SUM()。 现在我获得了超过5000个结果,每天的总和。

有人能以正确的方式帮助我吗?

1 个答案:

答案 0 :(得分:3)

你不应该有分组的发布日期(如果你发布日期分组..你将独立获得所有发布日期总和)

而且还不需要having子句..您的查询应该如下

SELECT     [Customer No_], SUM(Amount) AS SumDebitor
FROM         dbo.[3S Company A_S$Detailed Cust_ Ledg_ Entry]
WHERE     ([Posting Date] <= CONVERT(DATETIME, '2015-04-10 00:00:00', 102))
And  ([Customer No_] = '45')
GROUP BY [Customer No_]

或如下(如果您需要为所有客户计算)

SELECT     [Customer No_], SUM(Amount) AS SumDebitor
FROM         dbo.[3S Company A_S$Detailed Cust_ Ledg_ Entry]
WHERE     ([Posting Date] <= CONVERT(DATETIME, '2015-04-10 00:00:00', 102))
GROUP BY [Customer No_]