Retrieve top selling products - sql

I would like to receive top 5 selling products in quantity in an order from NorthWind database.
The database has a bunch of tables like Order, OrderDetails, Customers, etc. I was suggested to use Orders Details table below:
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.
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.

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;

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

SQL Query number of units in each category

Need help with an SQL Server query to get below results.
An SQL query to report how many units in each category have been ordered on each day of the week
This is current syntax
SELECT TOP 3 ProductID , ProductQty
FROM OrderDetails
ORDER BY ProductQty DESC;
Here is the image from the database
Any help is much appreciated.
Thank you
We can get your required result by dividing logic into two parts.
Firstly, get the product total count from order details
Secondly, we can assing category-wise rank to products with highest to lowest and pull the first 3 products from each category.
;WITH CTE_Data AS (
SELECT PD.PrdCategory AS PrdCategory, OD.ProductID AS ProductID, SUM(ProductQty) AS ProductQty
FROM OrderDetails OD (NOLOCK)
INNER JOIN ProductDetails PD (NOLOCK) ON OD.ProductID = PD.PrdId
GROUP BY PD.PrdCategory, ProductID
)
, CTE_Data2 AS(
SELECT PrdCategory, ProductID, ProductQty, ROW_NUMBER() OVER(PARTITION BY PrdCategory, ProductID ORDER BY ProductQty DESC) AS RowNo
FROM CTE_Data
)
SELECT ProductID, ProductQty
FROM CTE_Data2
WHERE RowNo IN (1,2,3)

SQL Query - second ID of a list ordered by date and ID

I have a SQL database with a list of Customer IDs CustomerID and invoices, the specific product purchased in each invoice ProductID, the Date and the Income of each invoice . I need to write a query that will retrieve for each product, which was the second customer who made a purchase
How do I do that?
EDIT:
I have come up with the following query:
SELECT *,
LEAD(CustomerID) OVER (ORDER BY ProductID, Date) AS 'Second Customer Who Made A Purchase'
FROM a
ORDER BY ProductID, Date ASC
However, this query presents multiple results for products that have more than two purchases. Can you advise?
SELECT a2.ProductID,
(
SELECT a1.CustomerID
FROM a a1
WHERE a1.ProductID = a2.ProductID
ORDER BY Date asc
LIMIT 1,1
) as SecondCustomer
FROM a a2
GROUP BY a2.ProductID
I need to write a query that will retrieve for each product, which was the second customer who made a purchase
This sounds like a window function:
select a.*
from (select a.*,
row_number() over (partition by productid order by date asc) as seqnum
from a
) a
where seqnum = 2;

SQL divide the column values to equal groups with ntile

I need to write sql query that divide the products to 3 equal groups by their price, (The cheapest products will be in the first group). For each group I have to present the price ranges it includes and the average units in stock.
I try to use ntile but I got stuck:
SELECT UnitPrice, NTILE(3) OVER (
ORDER BY UnitPrice ASC
) AS productGroup, UnitsInStock
FROM Products
You need to put a query on top of this one. Something like this:-
select productGroup, min(UnitPrice), max(UnitPrice), avg(UnitPrice)
from (
SELECT UnitPrice, NTILE(3) OVER (ORDER BY UnitPrice ASC) AS productGroup
, UnitsInStock
FROM Products
) t1
group by productGroup

SQL Query: SELECT MAX SUM quantity

How do i combine a SUM and MAX in a single query?
Lets say i have a orderrule:
ProductID \ Quantity
I Could say:
Select ProductID,SUM(Quantity) AS Sold
FROM Orderrule
GROUP BY ProductID
ORDER BY SUM(Quantity) Desc
However that would return all sales, and not just the most sold product (with quantity).
Try this
SELECT TOP(1)
*
FROM
(
Select
ProductID,
MAX(Quantity) As MaxQuantity,
SUM(Quantity) AS Sold
FROM Orderrule
GROUP BY ProductID
)AS X
ORDER BY Sold DESC
So there are two ways to do it - first to have a limit on the number of results, something likes:
select * from (your_select) where rownum = 1
the other one is to pick the one with the the highest value, which will require a subselect, something like:
having sum(quantity) =
(select max(sum_quan) from (select sum(Quantity) from orderrule group by Product_id))
SELECT TOP 1 ProductID, Sold FROM
(
SELECT ProductID, SUM(Quantity) AS Sold
FROM Orderrule
GROUP BY ProductID
) totals
ORDER BY Sold DESC

SQL GROUP BY on a sub query

I have a query that will return results from 2 tables into 1 using a UNION ALL, which all works as I need it to. However I need to run a GROUP BY and an ORDER BY on the returned dataset however I am getting many errors and I'm not sure how to solve it.
Here is my Query:
SELECT ProductID, Quantity
FROM BasketItems
UNION ALL
SELECT ProductID, Quantity
FROM OrderItems
This will return a results set such as this:
ProductID Quantity
15 2
20 2
15 1
8 5
5 1
I then want to run a GROUP BY on the ProductID field and then finally an ORDER BY DESC on the Quantity field. So in the final output, this particular results set will finally result in this:
ProductID
8
15
20
5
I can then run queries on this result set as I usually do
EDIT:
As stated above, but maybe not implied enough is that I will need to run queries on the returned results, which isn't working as you cannot run a query on a set of results that have an ORDER BY clause (so far as I gathered from the error list)
If you want more information on the problem, here it is:
From this results set, I want to get the products from the product table that they relate to
SELECT * FROM Products WHERE ID IN (
SELECT ProductID
FROM
(
SELECT ProductID, Quantity
FROM BasketItems
UNION ALL
SELECT ProductID, Quantity
FROM OrderItems
) v
GROUP BY ProductID
ORDER BY SUM(Quantity) DESC
)
However, I get this error: The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified.
The output of products need to be in the order that they are returned in the sub query (By quantity)
SELECT Products.*
FROM Products
INNER JOIN
(
SELECT ProductID, Sum(Quantity) as QuantitySum
from
(
SELECT ProductID, Quantity
FROM BasketItems
UNION ALL
SELECT ProductID, Quantity
FROM OrderItems
) v
GROUP BY ProductID
) ProductTotals
ON Products.ID = ProductTotals.ProductID
ORDER BY QuantitySum DESC
will this work?
SELECT ProductID
from
(
SELECT ProductID, Quantity
FROM BasketItems
UNION ALL
SELECT ProductID, Quantity
FROM OrderItems
) temp
GROUP BY temp.ProductID
ORDER BY SUM(temp.Quantity) desc
Here's a cte version (no live test so please excuse blunders)
EDIT
;WITH myInitialdata_cte(ProductID,Quantity)
AS
(
SELECT ProductID, Quantity FROM BasketItems
UNION ALL
SELECT ProductID, Quantity FROM OrderItems
)
SELECT b.ID
FROM
myInitialdata_cte a
INNER JOIN Products b ON
a.ProductID = b.ID
GROUP BY ProductID
ORDER BY SUM(a.Quantity) DESC