我的平均水平在where和havingsql中都不起作用

我的平均水平在where和havingsql中都不起作用,sql,sql-server,average,where-clause,having-clause,Sql,Sql Server,Average,Where Clause,Having Clause,因此,我必须为所有价格超过所有产品平均价格的产品显示产品名称、id产品和单价。这是我的问题 select ProductID, ProductName, UnitPrice from Products where UnitPrice in (select UnitPrice from Products where avg(UnitPrice)> UnitPrice) 但我得到的是erro,因为聚合平均价格(unitprice),当我将其替换为有其原因错误时。我能做什么 因此,我必须为所有

因此,我必须为所有价格超过所有产品平均价格的产品显示产品名称、id产品和单价。这是我的问题

select ProductID, ProductName, UnitPrice
from Products
where UnitPrice in
(select UnitPrice
from Products
where avg(UnitPrice)> UnitPrice)
但我得到的是erro,因为聚合平均价格(unitprice),当我将其替换为有其原因错误时。我能做什么

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

接近。使用子查询返回平均值,并仅将其用于比较:

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

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

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

我想你在找这样的东西

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;

我没有得到答案,结果是null@JessicaMaya . . . 首先,返回三列的查询不会返回
NULL
。其次,如果
UnitPrice
每行的
UnitPrice
相同或
NULL
,则此查询只能返回所有行。您的帖子需要完整引用错误,而不是解释错误。您不能编写任何您想要的SQL代码,并且希望SQL Server能够正确理解和执行它。可能先学习一些SQL语法。@SteveC:你认为我的代码中需要修正什么?