微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

SQL比较汇总平均值Northwind

如何解决SQL比较汇总平均值Northwind

我的问题特别涉及northwind数据库,因此我没有提供任何可复制的示例/数据集。

我要选择所有单价大于每个类别平均单价的产品,但不包括给定产品所属的一个类别。我尝试了两种不同的方法,到目前为止,没有一种方法可以达到预期的效果

这个返回一个汇总的数据集,但是我不知道如何比较所有类别的每个UnitPrice和所有类别的平均单价,除了给定产品所属的那个

select 
p.ProductName,UnitPrice,t.mean,t.CategoryID from Products as p
inner join
(select avg(UnitPrice) as mean,CategoryID from Products
group by CategoryID) as t
on p.CategoryID = t.CategoryID

在这里,我可以将UnitPrice与所有类别的总平均值进行比较,但不排除给定产品所属的类别

SELECT x.ProductName,AVG(x.UnitPrice) AS average
FROM Products x
GROUP BY x.CategoryID,x.ProductName
Having AVG(x.UnitPrice)> 
(select AVG(UnitPrice) from Products)

所需的结果应该看起来像

enter image description here

谢谢。

解决方法

您可以使用横向连接来表达这一点:

select p.*,a.avg_unitprice
from products p
cross apply (
    select avg(p1.unitprice) avg_unitprice
    from products p1
    where p1.categoryid <> p.categoryid
) a
where p.unitprice > a.avg_unitprice 

这会将每种产品的单价与其他类别中所有产品的平均单价进行比较。

另一方面,如果您想要价格高于其他类别的所有平均价格的产品,那么not exists似乎更合适:

select p.*
from products p
where not exists (
    select 1
    from products p1
    where p1.categoryid <> p.categoryid
    group by p1.categoryid
    having avg(p1.unitprice) >= p.unitprice
)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。