I have some task that I should do it with sql. Below is the function I currently use.
(SELECT ProductName, sum(Quantity*Price) Revenue, Country
FROM products p
JOIN orderdetails d
ON p.ProductID = d.ProductID
JOIN orders o
ON o.OrderID = d.OrderID
JOIN customers c
ON c.CustomerID = o.CustomerID
WHERE Country =
(
SELECT DISTINCT Country
FROM customers
LIMIT 1
)
GROUP BY ProductName
ORDER BY Revenue DESC
LIMIT 1)
UNION
(SELECT ProductName, sum(Quantity*Price) Revenue, Country
FROM products p
JOIN orderdetails d
ON p.ProductID = d.ProductID
JOIN orders o
ON o.OrderID = d.OrderID
JOIN customers c
ON c.CustomerID = o.CustomerID
WHERE Country =
(
SELECT DISTINCT Country
FROM customers
LIMIT 1,1
)
GROUP BY ProductName
ORDER BY Revenue DESC
LIMIT 1)
UNION
(SELECT ProductName, sum(Quantity*Price) Revenue, Country
FROM products p
JOIN orderdetails d
ON p.ProductID = d.ProductID
JOIN orders o
ON o.OrderID = d.OrderID
JOIN customers c
ON c.CustomerID = o.CustomerID
WHERE Country =
(
SELECT DISTINCT Country
FROM customers
LIMIT 2,1
)
GROUP BY ProductName
ORDER BY Revenue DESC
LIMIT 1)
My task is "Find best selling products based on revenue for each country!"
The result I want is below:
ProductName | Revenue | Country |
---|---|---|
Tofu | 279 | Argentina |
Côte de Blaye | 18445 | Austria |
You can access the data I use from this link RawDatabase
the sample data that I use is like this
ProdName | Country | Revenue |
---|---|---|
coco | Argentina | 120 |
bread | Austria | 10000 |
crunch | Austria | 13265 |
Cote de Blaye | Austria | 18445 |
milk | Argentina | 254 |
Tofu | Argentina | 279 |
From this data I want to select only the best product for each country by revenue. In the data there were 21 country. What should I do so I can get the result below
ProductName | Revenue | Country |
---|---|---|
Tofu | 279 | Argentina |
Côte de Blaye | 18445 | Austria |
The only way in my mind is only filtering the data by each country then get the best product then union all of them like the code I give on top. I wonder if there's another way.