【笔记】join using&AVG

oracle using

在oracle中,using用于简化连接查询,只有当查询是等值连接和连接中的列必须具有相同的名称与数据类型时,才能使用using关键字进行简化

比如原来是

select s.user_id as user_id ,
sum(s.quantity * p.price) as spending
from Sales s join Product p on s.product_id = p.product_id
group by s.user_id
order by sum(s.quantity * p.price) desc,s.user_id asc

可以写成

select s.user_id as user_id ,
sum(s.quantity * p.price) as spending
from Sales s join Product p USING(product_id)
group by s.user_id
order by sum(s.quantity * p.price) desc,s.user_id asc

avg

对列进行AVG()求平均值时,会自动跳过NULL的行
即如果有'[1],[2],[3],NULL,NULL',得到的平均值是2,而不是1.2
可以使用COALESCE(),其作用就是把NULL值转换为其他值,像是这样用
COALESCE(列名,'0')
这个时候就是1.2了

如果要查询计算最大值比平均值的情况,则可以直接

select a.order_id
  from OrdersDetails a
 group by a.order_id
HAVING max(a.quantity) > 
(select max(avg(b.quantity))
from OrdersDetails b
group by b.order_id)
posted @ 2022-08-23 21:34  DbWong_0918  阅读(57)  评论(0)    收藏  举报