在没有HAVING子句的情况下重写此SQL查询?

时间:2017-07-13 16:22:20

标签: mysql select subquery views inline

以下是原始查询:

select flavor, max(price) mp 
    from Product 
    where flavor != 'chocolate' 
    group by flavor having avg(price) < 4
    order by flavor;

我的任务是在没有HAVING子句的情况下重写这个查询,但我仍然在学习这些东西,而且我不确定如何准确地解决这个问题。作为提示,我被告知使用内联视图,但我的查询一直出错。

以下是我写的查询:

select flavor, max(price) mp from (select flavor, price, avg(price) ap from Product where flavor != 'chocolate' group by flavor,price) prod where ap < 4 group by flavor order by flavor;

我的结果中还有一行。我的查询有什么不一样的?

1 个答案:

答案 0 :(得分:2)

好像你需要这样的东西:

select prod.flavor, prod.MaxPrice
from (
    select flavor, max(price) AS MaxPrice, avg(price) AS AvgPrice
    from Product 
    where flavor != 'chocolate' 
    group by flavor) prod 
where prod.AvgPrice < 4 
order by flavor;