SQL查询 - 理解语法

Ami*_*mit 3 sql sql-server

我想按数量展示最畅销的产品

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
Run Code Online (Sandbox Code Playgroud)

因为总和(数量)= 225

我用了:

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
                )
  )  
Run Code Online (Sandbox Code Playgroud)

我收到了错误: "Cannot perform an aggregate function on an expression containing an aggregate or a subquery"

请解释为什么语法在这里失败,以便将来我会通过知道正确的语法来编写适当的查询.也给我正确的查询.

提前谢谢大家.

编辑

我正在尝试以下查询

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))
Run Code Online (Sandbox Code Playgroud)

Joe*_*lli 5

我认为这是你想要达到的目的:

select top 1 p.product_name, sum(od.quantity) as total_quantity
    from products p
        inner join [order details] od
            on p.productid = od.productid
    group by p.productid, p.product_name
    order by total_quantity desc
Run Code Online (Sandbox Code Playgroud)