当前位置:网站首页>MySQL窗口函数 OVER()函数介绍
MySQL窗口函数 OVER()函数介绍
2022-08-03 16:02:00 【飞Link】
前期准备的数据
# 创建数据库
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);
边栏推荐
猜你喜欢
随机推荐
Leetcode76. Minimal Covering Substring
详谈RDMA技术原理和三种实现方式
我写了个”不贪吃蛇“小游戏
【深度学习】今日bug(8月2)
MarkDown常用代码片段和工具
Windows 事件查看器记录到 MYSQL
我在滴滴做开源
使用Make/CMake编译ARM裸机程序(基于HT32F52352 Cortex-M0+)
[微信小程序开发者工具] × #initialize
Leetcode76. 最小覆盖子串
spark入门学习-1
mysql delete execution error: You can't specify target table 'doctor_info' for update in FROM clause
想进阿里?先来搞懂一下分布式事务
用户侧有什么办法可以自检hologres单表占用内存具体是元数据、计算、缓存的使用情况?
Kubernetes 笔记 / 任务 / 管理集群 / 用 kubeadm 管理集群 / 配置一个 cgroup 驱动
泰山OFFICE技术讲座:段落边框的绘制难点在哪里?
基于DMS的数仓智能运维服务,知多少?
MATLAB gcf figure save image with black background/transparent background
To participate in sweepstakes, incoming new programmers magazine welfare!
[Code Hoof Set Novice Village 600 Questions] Define a function as a macro









![[Unity Getting Started Plan] Basic Concepts (8) - Tile Map TileMap 02](/img/45/96af4ca21329964808a4c8f2b8272c.png)