SQL Max(数量*产品价格)

时间:2019-01-28 01:13:28

标签: sql ms-access max

我正在尝试回答以下问题:哪个产品ID和产品名称带来的收入超过商店中产品平均收入。

我有以下代码:

Select ProductName, SupplierName, MAX(Quantity*ProductPrice) as TotalRev
From Products
Where MAX(TotalRev) > AVG(TotalRev)

但是这会导致错误。

样本数据

ProductID  ProductName  SupplierName ProductType Quantity ProductPrice
10001      GreenJacket  GAP          Jackets     100      $10
10002      StarEarrings Oldnavy      Accessories 200      $5
10003     YellowDress   BRP          Dress       150      $10

理想情况下,我希望代码吐出ProductID和Product名称,以便产品带来比平均收入更多的收入。

1 个答案:

答案 0 :(得分:1)

您需要一个having子句和一个子查询:

Select ProductId, ProductName,
       SUM(Quantity*ProductPrice) as TotalRev
From Products
group by ProductId, ProductName
having SUM(Quantity*ProductPrice) >= (select avg(revenue) 
                                      from (select sum(p2.quantity * p2.ProductPrice) as revenue
                                            from products as p2
                                            group by p2.ProductId, p2.ProductName
                                           ) as p3
                                      );

我建议您在having子句中运行子查询,以便您完全了解它在做什么。