【问题标题】:My average didnt work both in where and having SQL我的平均值在 where 和 SQL 中都不起作用
【发布时间】:2020-10-20 15:46:03
【问题描述】:

所以我必须为价格超过所有产品平均价格的所有产品显示产品名称、产品 ID 和单价。这是我的查询

select ProductID, ProductName, UnitPrice
from Products
where UnitPrice in
(select UnitPrice
from Products
where avg(UnitPrice)> UnitPrice)

但是我得到的是错误,因为聚合平均(单价),当我用它的原因错误替换它时。我该怎么办?

【问题讨论】:

  • Edit 你的帖子要完整引用错误,而不是解释它们。
  • 您无法编写任何您想要的 SQL 代码,并期望 SQL Server 能够正确理解和执行它。大概先学点SQL语法吧。

标签: sql sql-server average where-clause having-clause


【解决方案1】:

您可以为此使用窗口函数而不是子查询:

select *
from (
    select ProductID, ProductName, UnitPrice, avg(unitPrice) over() avgUnitPrice
    from Products
) p
where UnitPrice > avgUnitPrice

【讨论】:

  • @SteveC:你认为我的代码需要修复什么?
【解决方案2】:

我认为您正在寻找类似的东西

with avg_cte(avg_price) as (
    select avg(UnitPrice)
    from Products)
select ProductID, ProductName, UnitPrice
from Products p
     cross join avg_cte a
where p.UnitPrice>a.avg_price;

【讨论】:

    【解决方案3】:

    所以我必须为所有价格超过所有产品平均价格的产品显示产品名称、产品id和单价。

    关闭。使用子查询返回平均值并将其用于比较:

    select ProductID, ProductName, UnitPrice
    from Products p
    where UnitPrice > (select avg(UnitPrice) from Products);
    

    【讨论】:

    • 我没有得到答案,结果为空
    • @JessicaMaya 。 . .首先,返回三列的查询不会返回NULL。其次,如果UnitPrice 相同或NULL 在每一行上,此查询只能返回UnitPrice 的所有行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-01
    • 1970-01-01
    • 2015-09-29
    相关资源
    最近更新 更多