我写了以下查询:

SELECT CLIENT.CLIENTNO, CLIENT.CNAME, TOTALS.TOTAL
FROM CLIENT, (SELECT CLIENTNO, SUM(AMOUNT) AS TOTAL
              FROM PURCHASE GROUP BY CLIENTNO) TOTALS
WHERE CLIENT.CLIENTNO = TOTALS.CLIENTNO AND ROWNUM <= 1
ORDER BY TOTALS.TOTAL DESC;

但是,这给了我错误的答案,但是如果我删除了ROWNUM <= 1子句,则正确的答案将位于结果集的顶部。

那么,我可以在此查询中进行哪些更改以使其产生正确的答案?

谢谢,
亚历克斯

编辑:忘了说我只希望查询返回结果集中的第一个结果。

最佳答案

ROWNUM过滤器在排序之前应用。您需要做的是:

SELECT * FROM (
  SELECT CLIENT.CLIENTNO, CLIENT.CNAME, TOTALS.TOTAL
  FROM CLIENT, (SELECT CLIENTNO, SUM(AMOUNT) AS TOTAL
                  FROM PURCHASE GROUP BY CLIENTNO) TOTALS
  WHERE CLIENT.CLIENTNO = TOTALS.CLIENTNO
  ORDER BY TOTALS.TOTAL DESC
)
WHERE ROWNUM <= 1

09-08 10:34