1

I have the below simple query which shows the sum of valuehome by el2.

If i add another column to my query (see select statement 2) and say only show me valuehome where the due date is before today, i.e. it is overdue, I lose my sum on the valuehome as the results show a row for each due date

How do I maintain the sum of valuehome so that i see one result for valuehome even if there is more than one due date.

SELECT     TOP (100) PERCENT el2, statpay, SUM(valuehome) AS Expr1
FROM         dbo.MBO450
GROUP BY el2, statpay
HAVING      (el2 LIKE 'C%') AND (statpay = 84)
ORDER BY el2


SELECT     TOP (100) PERCENT el2, statpay, SUM(valuehome) AS Expr1, duedate
FROM         dbo.MBO450
GROUP BY el2, statpay, duedate
HAVING      (el2 LIKE 'C%') AND (statpay = 84) AND (duedate <= CONVERT(DATETIME, '2013-07-24 00:00:00', 102))
ORDER BY el2

Thanks Nenad - thats brilliant help - do you know how i would change my static date in the where statement

Don't add duedate to GROUP BY and HAVING - filter the rows in WHERE condition before grouping :

SELECT el2, statpay, SUM(valuehome) AS Expr1
FROM dbo.MBO450
WHERE duedate <= CONVERT(DATETIME, '2013-07-24 00:00:00', 102))  

so that the static date is todays date?

4

1 回答 1

0

不要在分组之前添加和 - 过滤条件duedateGROUP BYHAVING行:WHERE

SELECT el2, statpay, SUM(valuehome) AS Expr1
FROM dbo.MBO450
WHERE duedate <= CONVERT(DATETIME, '2013-07-24 00:00:00', 102))
GROUP BY el2, statpay
HAVING (el2 LIKE 'C%') AND (statpay = 84) 
ORDER BY el2

PS:TOP (100) PERCENT没用

PPS:你也可以做移动el2statpay条件到WHERE

PPPS:今天更换WHERE duedate <= GETDATE()为动态

于 2013-07-24T15:59:51.297 回答