5

我已经构建了这个 SQL 查询,它搜索所有保单号码并返回所有多个 PPOLNO 货币值的总和:

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

我正在寻找的只是在 SUM >= 特定值时才返回它们。这可能吗?如何?我试过这个:

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

但无济于事。我也刚刚尝试输入 WHERE SUM >= 5000,但同样没有。

任何帮助将不胜感激。

  • 乔什
4

2 回答 2

25

每当您需要对聚合(即SUM)执行“WHERE”子句时,都需要使用该HAVING子句。

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
于 2013-05-01T14:50:50.050 回答
2

Where子句中的谓词在聚合之前应用,要在聚合之后应用谓词(过滤器),请使用Having子句...尝试

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 
于 2013-05-01T14:50:38.597 回答