SQL查询 - 理解语法

时间:2010-09-20 19:13:18

标签: 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

因为总和(数量)= 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
                )
  )  

我收到错误:"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))

4 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

看起来像选择最大值(SUM(数量))是错误的。总和的最大值没有任何意义。你的意思是max(Quantity)?

答案 2 :(得分:0)

试试这个:

select 'Product By Quantity' + ProductName  from Products p
join 
(
select top 1 sum(Quantity) sq, od.ProductId 
from [Order Details] od
group by od.ProductId 
order by 1 desc
) bsp on p.productid = bsp.ProductId

bsp代表畅销产品

答案 3 :(得分:0)

试试这个:

SELECT      TOP 1
            SUM(o.Quantity)
            ,p.ProductName
FROM        [Order Details] AS o
INNER JOIN  [Products] AS p ON p.ProductID = o.ProductID
GROUP BY    p.ProductID
            ,p.ProductName
ORDER BY    SUM(o.Quantity) DESC