Search code examples
sqloracle-databaseoracle10g

Select first result only


I have written the following query:

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;

However it is giving me the wrong answer, but if I remove the ROWNUM <= 1 clause, then the correct answer is at the top of the result set.

So what can I change in this query to make it produce the correct answer?

Thanks, Alex.

EDIT: Forgot to say that I only want the query to return the the first result in the result set.


Solution

  • The ROWNUM filter applies before the sorting. What you need to do is this:

    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