I want to display greatest selling product by quantity
Product Table
ProductID ProductName
1 AA
2 BB
3 CC
[Order Details] Table
OrderID ProductID Quantity DateOfOrder
1 1 10 SomeDate
2 1 100 ,,
3 2 15 ,,
4 1 15 ,,
5 2 20 ,,
6 2 30 ,,
7 1 100 ,,
Expected Output
Product By Quantity AA
Because sum(quantity)= 225
I used:
select 'Product By Quantity' + ProductName
from
Products
where ProductID in
(select
ProductID
from
[Order Details] det
where Quantity=
(
select max(SUM(Quantity))
from [Order Details] od
where
od.ProductID=det.ProductID
)
)
I got error : "Cannot perform an aggregate function on an expression containing an aggregate or a subquery"
Please explain me why the syntax fails here so that in future i will write appropriate query by knowing the correct syntax.Also give me the correct query.
Thank you everybody in advance.
Edit
I was trying for the following query
SELECT 'Best Selling Product'+ProductName
FROM
Products
WHERE ProductID =
(
SELECT ProductID
FROM [Order Details]
GROUP BY ProductID
HAVING SUM(Quantity) = (
SELECT MAX(SQ)
FROM (
SELECT SUM(Quantity) as SQ
FROM [Order Details]
GROUP BY ProductID
) AS OD))