Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only return rows if sum is greater than a value

Tags:

sql

sum

db2

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
like image 891
ResourceReaper Avatar asked May 01 '13 14:05

ResourceReaper


2 Answers

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
like image 151
Derek Kromm Avatar answered Nov 15 '22 00:11

Derek Kromm


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 
like image 40
Charles Bretana Avatar answered Nov 14 '22 23:11

Charles Bretana