Subqueries: Any/All

1. Subquery Any

Syntax:

-- any
-- remove inner order by
select EnglishProductName, ListPrice from DimProduct
where ListPrice > any(select avg(ListPrice) from DimProduct
group by ProductSubcategoryKey)
order by ListPrice asc

Analysis:

It’s asking for a list of products whose price is greater than any of the average list prices from the subquery. In this case, the lowest average is 7.95. Therefore it’s showing all of those products with a ListPrice of more than 7.95.

2. Subquery All

Syntax:

-- all with nulls
select EnglishProductName, ListPrice from DimProduct
where ListPrice > all(select avg(ListPrice) from DimProduct
group by ProductSubcategoryKey)
order by ListPrice asc

Analysis:

It’s looking for all products with a price greater than all of the average prices from the subquery. In other words, it’s looking for all those productes whose price is greater than the highest of the subcategory average prices.

Caution:

Do not let null value join into the comparison, otherwise, you will get incorrect results.

But there was an average price with a null value, A null value, if you like, is indeterminate --- so it cannot be guaranteed to really be the maximum. The maximum is unknown, so the outer query fails to show any records.

Solution:

Adding a Having clause to the subquery --- this is going to eliminate all average prices with null values.

-- all without nulls
select EnglishProductName, ListPrice from DimProduct
where ListPrice > all(select avg(ListPrice) from DimProduct group by 
ProductSubcategoryKey having avg(ListPrice) is not null)
order by ListPrice asc

转载于:https://www.cnblogs.com/aot/p/3148735.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值