仅选择第一个结果

时间:2011-10-20 09:48:27

标签: sql oracle oracle10g

我写了以下查询:

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子句,那么正确的答案就在结果集的顶部。

那么我可以在此查询中更改哪些内容以使其生成正确的答案?

谢谢, 亚历克斯。

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

2 个答案:

答案 0 :(得分:16)

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 

答案 1 :(得分:3)

将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;