Home > Net >  Retrieve top selling products
Retrieve top selling products

Time:03-31

I would like to receive top 5 selling products in quantity in an order from enter image description here

Now, I tried the following:

WITH cte AS (
    SELECT 
       OrderID,
       Quantity,
       ProductID,
       ROW_NUMBER() OVER(PARTITION BY OrderID ORDER BY OrderID) as row_num
    FROM [Order Details] 
)

SELECT * 
FROM cte 
WHERE row_num IN (SELECT row_num FROM cte WHERE row_num <=10)
ORDER BY  OrderID;

Thought this retrieves 10 rows now for each order, they are not ordered based on sold quantities and top sold products are not retrieved properly as for some orders the top sold was beyond the first top 10 rows based on row number I got with ROW_NUMBER() function in SQL.

enter image description here

Edit: For example, if I have 10 orders each with 20 products, then I want top 5 each each product, so the result table should have 50 rows total.

CodePudding user response:

After your edits:

WITH cte AS (
SELECT 
   OrderID,
   Quantity,
   ProductID,
   ROW_NUMBER() OVER(PARTITION BY OrderID ORDER BY Quantity DESC) as row_num
FROM [Order Details] 
)

SELECT * 
FROM cte 
WHERE row_num <= 5
ORDER BY  OrderID;

CodePudding user response:

You should do a
SELECT DISTINCT productid FROM OrderDetails ORDER BY quantity GROUP BY productId LIMIT 5
At least this is the mysql syntax.

  • Related