简体   繁体   中英

Only return rows if sum is greater than a value

I have built this SQL Query which searches for all policy numbers and returns a sum of all multiple PPOLNO's currency values :

SELECT PPOLNO, SUM(PPRMPD) AS SUM 
FROM PFNTLPYMTH 
WHERE SUM(PPRMPD) >= 5000 
  AND  ((PYEAR=2012 AND PMONTH >=3 
  AND PDAY >=27) OR (PYEAR=2013 
  AND PYEAR <=3 AND PDAY<=27))
GROUP BY PPOLNO

What I'm looking at doing is only returning them if the SUM >= a specific value. Is this possible and how? I tried this:

SELECT PPOLNO, SUM(PPRMPD) AS SUM FROM PFNTLPYMTH
WHERE SUM(PPRMPD) >= 5000 AND ((PYEAR=2012 AND PMONTH >=3 AND PDAY >=27) OR (PYEAR=2013 
AND PYEAR <=3 AND PDAY<=27)) GROUP BY PPOLNO

But to no avail. I've also just tried putting in WHERE SUM >= 5000, but again, nothing there.

Any help would be greatly appreciated.

  • Josh

Whenever you need to do a "WHERE" clause on an aggregate (which SUM is), you need to use the HAVING clause.

SELECT PPOLNO, SUM(PPRMPD) AS SUM FROM PFNTLPYMTH
WHERE ((PYEAR=2012 AND PMONTH >=3 AND PDAY >=27) OR (PYEAR=2013 
AND PYEAR <=3 AND PDAY<=27)) GROUP BY PPOLNO
HAVING SUM(PPRMPD) >= 5000

Predicates in the Where clause are applied before aggregation, To apply a predicate (filter) after aggregation, use a Having clause... try

SELECT PPOLNO, SUM(PPRMPD) AS SUM 
FROM PFNTLPYMTH 
WHERE  ((PYEAR=2012 AND PMONTH >=3 
  AND PDAY >=27) OR (PYEAR=2013 
  AND PYEAR <=3 AND PDAY<=27))
GROUP BY PPOLNO
Having SUM(PPRMPD) >= 5000 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM