MySQL窗口函数 OVER()函数介绍

前期准备的数据

# 创建数据库
create database if not exists shopping charset utf8;
# 选择数据库
use shopping;
# 创建产品表
create table product
(
    id      int primary key,
    name    varchar(20),
    price   int,
    type varchar(20),
    address varchar(20)
);
# 插入产品数据
insert into shopping.product(id, name, price, type, address) values
    (1,商品1,200,type1,北京),
    (2,商品2,400,type2,上海),
    (3,商品3,600,type3,深圳),
    (4,商品4,800,type1,南京),
    (5,商品5,1000,type2,成都),
    (6,商品6,1200,type3,武汉),
    (7,商品7,1400,type1,黑龙江),
    (8,商品8,1600,type2,黑河),
    (9,商品9,1800,type3,贵州),
    (10,商品10,2000,type1,南宁);

一、描述

OVER()的意思就是所有的数据都在窗口中

二、实例

    OVER() 意思是所有的数据都在窗口中
# 计算所有商品的平均价格
select *,avg(price) over () from product;
    OVER()用于将当前行与一个聚合值进行比较
# 计算商品价格与平均价格之差
select *,price-avg(price) over () from product;
    OVER()和COUNT()组合
# 计算所有商品数量
select *,count(id) over() from product;
    一句SQL中使用两个窗口函数
# 在商品表的基础上,添加平均价格和总金额两列
select *,avg(price) over (),sum(price) over () from product;
    窗口函数和where一起使用
# 计算type1类型和type2类型的平均价格
select
       *, avg(price) over()
from product
where type in (type1,type2);
    在过滤条件中不能使用OVER()
# 查询所有商品中,价格高于平均价格的商品(报错)
select
    *,
    avg(price) over()
from product
where price > avg(price) over();
# 查询所有商品中,价格高于平均价格的商品
select
    *,
    avg(price) over()
from product
where price > (select avg(price) from product);
经验分享 程序员 微信小程序 职场和发展