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

How to limit the results to 1 row in Oracle SQL

本问题已经有最佳答案,请猛点这里访问。

我有一个成功运行的查询

1
2
3
4
SELECT customerNumber
FROM ORDERS
GROUP BY customerNumber
ORDER BY count(orderNumber) DESC

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

1
ORA-00933: SQL command not properly ended

以下是我的尝试:

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

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


在Oracle中,您需要先进行排序,然后选择rownum。因此,需要嵌套返回排序数据的查询,并将筛选WHERE子句带到外部。

1
2
3
4
5
6
7
8
SELECT * FROM
(
 SELECT customerNumber
 FROM ORDERS
 GROUP BY customerNumber
 ORDER BY count(orderNumber) DESC
) resultSet
WHERE ROWNUM=1;


您可以组合分组和窗口函数来完成这一点。

1
2
3
4
5
6
7
8
9
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;

与简单的"只给我一行"不同的是,这还将返回具有相同订单数的多个客户。如果您不想这样做,用row_number()替换dense_rank()


必须将where条件置于order by之前(但似乎排序完成后需要第一行)

所以你应该用一个选择这个wya

1
2
3
4
5
6
7
  select * from (
    SELECT customerNumber
    FROM ORDERS
    GROUP BY customerNumber
    ORDER BY count(orderNumber) DESC
  ) t
  WHERE ROWNUM=1;