【问题标题】:Rewrite this SQL query without HAVING clause?在没有 HAVING 子句的情况下重写这个 SQL 查询?
【发布时间】:2017-07-13 16:22:19
【问题描述】:

这是原始查询:

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 行。我的查询有什么不一样的地方?

【问题讨论】:

  • 您应该使用 AVG 计算 MAX;像您现在一样选择price 将导致为每种产品风味选择有效的随机价格。 ...无论如何使用 HAVING 有什么问题?
  • 您是否尝试将平均值放在where 过滤器上?
  • 这是一个让类更好地理解子查询和内联视图的练习。我终于明白了,@Tom 的想法是对的。

标签: mysql select subquery views inline


【解决方案1】:

看来你需要类似的东西:

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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-09
    • 1970-01-01
    • 1970-01-01
    • 2018-06-27
    • 1970-01-01
    • 2011-12-07
    相关资源
    最近更新 更多