簡體   English   中英

SQL 查詢聚合可能不會出現在 WHERE 子句 (AVG) 中

[英]SQL Query aggregate may not appear in WHERE clause (AVG)

嗨,我找不到如何解決此問題的解決方案。

聚合可能不會出現在 WHERE 子句中,除非它位於 HAVING 子句或 select 列表中包含的子查詢中,並且被聚合的列是外部引用。

select p.ProductName, p.UnitPrice
from [DESKTOP-509LB9L\MSSQLSERVER01].northwind.dbo.products p
where p.UnitPrice > AVG(p.UnitPrice)
group by p.UnitPrice

應該是這樣的: AVG 是 28.3 所以 UnitPrice 高於 28.3

ProductName                        UnitPrice
Uncle Bob's Organic Dried Pears     30,00
Northwoods Cranberry Sauce          40,00
Mishi Kobe Niku                     97,00
Ikura                               31,00
Queso Manchego La Pastora           38,00
Alice Mutton                        39,00

也沒有工作

select p.ProductName, p.UnitPrice
from [DESKTOP-509LB9L\MSSQLSERVER01].northwind.dbo.products p
group by p.UnitPrice
having p.UnitPrice > AVG(p.UnitPrice)

改用子查詢:

select p.ProductName, p.UnitPrice
from [DESKTOP-509LB9L\MSSQLSERVER01].northwind.dbo.products p
where p.UnitPrice > (select avg(p2.UnitPrice)
                     from [DESKTOP-509LB9L\MSSQLSERVER01].northwind.dbo.products p2
                    );

您需要使用子查詢來計算平均值,然后再將其與單價進行比較

select p.ProductName, p.UnitPrice
from northwind.dbo.products p
where p.UnitPrice>
(
    select AVG(p2.UnitPrice)
    from northwind.dbo.products p2
    group by p2.ProductName
    having p2.ProductName = p.ProductName
)

您應該確保您的產品名稱是唯一的或使用產品密鑰而不是名稱

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM