1

I have a table named "items" where are stored information about each product sold in each order, but I want to retrieve top 10 orders with max quantity of products sells. I've executed a SELECT statement to retrieve number of products sold in each orders but I don't know How I can retrieve only TOP 10 orders. Thanks.

SELECT   codigo_orden AS ORDER_ID, COUNT(codigo_producto) AS PRODUCTS_SOLD
FROM     cs_items
GROUP BY codigo_orden
ORDER BY 2 DESC;

enter image description here

But I just want to retrieve TOP 10 most products sold!! Something like that:

enter image description here

Mark Rotteveel
  • 90,369
  • 161
  • 124
  • 175

2 Answers2

2

If you are using Oracle 12c, you can use the row limiting clause, something like

SELECT   codigo_orden AS ORDER_ID, COUNT(codigo_producto) AS PRODUCTS_SOLD
FROM     cs_items
GROUP BY codigo_orden
ORDER BY 2 DESC
FETCH FIRST 10 ROWS ONLY

If you are not using 12c, then you can use a window function, for example

select order_id, products_sold
from (
    SELECT   codigo_orden AS ORDER_ID, 
             COUNT(codigo_producto) AS PRODUCTS_SOLD,
             rank() over (order by count(codigo_producto) ) as rnk
    FROM     cs_items
    GROUP BY codigo_orden
)
where rnk <= 10
order by products_sold

You might need to use dense_rank() vs rank(), depending on how you want to handle ties.

BobC
  • 3,940
  • 1
  • 11
  • 14
  • Thanks but I'm using Oracle 11g. –  Mar 01 '17 at 21:38
  • @Rattlesnake. I have expanded my answer based on your comment. – BobC Mar 01 '17 at 21:47
  • From the OP's answer to follow-up questions, and from the example he provided, it seems he will need `row_number()` rather than `rank()` or `dense_rank()`. – mathguy Mar 01 '17 at 22:32
2

Try the following:

select ORDER_ID, PRODUCTS_SOLD
from (
SELECT   codigo_orden AS ORDER_ID, COUNT(codigo_producto) AS PRODUCTS_SOLD
FROM     cs_items
GROUP BY codigo_orden
ORDER BY 2 DESC)
WHERE ROWNUM <= 10;
Stephan Lechner
  • 34,359
  • 4
  • 30
  • 55