如何在Oracle SQL中将结果限制为1行

时间:2016-12-19 10:48:03

标签: oracle

我已成功运行此查询

SELECT customerNumber
FROM ORDERS 
GROUP BY customerNumber 
ORDER BY count(orderNumber) DESC

但是当我尝试将返回的行数限制为1时,我收到以下错误

ORA-00933: SQL command not properly ended 

这是我尝试过的:

SELECT customerNumber
FROM ORDERS 
GROUP BY customerNumber 
ORDER BY count(orderNumber) DESC
fetch first 1 row only;

SELECT customerNumber
FROM ORDERS 
GROUP BY customerNumber 
ORDER BY count(orderNumber) DESC
WHERE ROWNUM=1;

3 个答案:

答案 0 :(得分:5)

在Oracle中,您需要先进行排序,然后选择rownum。因此,您需要嵌套返回已排序数据的查询,并在外部采用过滤WHERE子句。

SELECT * FROM
(
 SELECT customerNumber
 FROM ORDERS 
 GROUP BY customerNumber 
 ORDER BY count(orderNumber) DESC
) resultSet
WHERE ROWNUM=1;

答案 1 :(得分:1)

您可以组合分组和窗口功能来完成此任务。

select customernumber, num_orders
from (
  SELECT customerNumber, 
         count(*) as num_orders,
         dense_rank() over (order by count(*) desc) as rnk
  from orders
  group by customerNumber
) t
where rnk = 1;

简单的“让我只有一行”的不同之处在于,它还将返回具有相同订单数量的多个客户。如果您不想这样做,请将dense_rank()替换为row_number()

答案 2 :(得分:0)

where条件必须放在order by之前(但似乎你需要在完成排序之后的第一行)

所以你应该选择这个wya

  select * from (
    SELECT customerNumber
    FROM ORDERS 
    GROUP BY customerNumber 
    ORDER BY count(orderNumber) DESC
  ) t 
  WHERE ROWNUM=1;