Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to limit the results to 1 row in Oracle SQL [duplicate]

Tags:

oracle

I've this query which runs successfuly

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

But when I try to limit the number of rows returned to 1, I get the following error

ORA-00933: SQL command not properly ended 

Here's what I've tried :

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

and

SELECT customerNumber
FROM ORDERS 
GROUP BY customerNumber 
ORDER BY count(orderNumber) DESC
WHERE ROWNUM=1;
like image 932
Satwik Avatar asked Dec 19 '16 10:12

Satwik


2 Answers

In Oracle you need to do the ordering first and then select rownum. Thus, you need to nest the query which returns the sorted data and take the filtering WHERE clause outside.

SELECT * FROM
(
 SELECT customerNumber
 FROM ORDERS 
 GROUP BY customerNumber 
 ORDER BY count(orderNumber) DESC
) resultSet
WHERE ROWNUM=1;
like image 91
Radu Gheorghiu Avatar answered Nov 09 '22 03:11

Radu Gheorghiu


You can combine grouping and window functions to accomplish this.

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;

The difference to a simple "get me only one row" is that this will also return multiple customers that have the same number of orders. If you don't want that, replace dense_rank() with row_number()

like image 20
a_horse_with_no_name Avatar answered Nov 09 '22 01:11

a_horse_with_no_name