当前位置:网站首页>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);
边栏推荐
猜你喜欢
Common distributed theories (CAP, BASE) and consensus protocols (Gosssip, Raft)
[Unity Getting Started Plan] Basic Concepts (8) - Tile Map TileMap 02
MATLAB | 一种简易的随机曼陀罗图形生成函数
参与便有奖,《新程序员》杂志福利来袭!
《安富莱嵌入式周报》第276期:2022.07.25--2022.07.31
Awesome!Coroutines are finally here!Thread is about to be in the past
罗克韦尔AB PLC RSLogix5000中创建新项目、任务、程序和例程的具体方法和步骤
元宇宙系列--Value creation in the metaverse
一个文件管理系统的软硬件配置清单
深度学习GPU最全对比,到底谁才是性价比之王?
随机推荐
DC-DC 2C (40W/30W) JD6606SX2 power back application
世界顶级级架构师编写2580页DDD领域驱动设计笔记,属实有牌面
【QT】Qt项目demo:数据在ui界面上显示,鼠标双击可弹窗显示具体信息
Convex Optimization of Optimal Power Flow (OPF) in Microgrids and DC Grids (Matlab Code Implementation)
JD6606SP5_JD6606SSP_JD6606SASP_JD6621W7百盛新纪元授权代理商
30W 2C(JD6606S + FP6652X2)BOM
leetcode: 899. Ordered Queue [Thinking Question]
小熊派——无线联网开发
GTK实现旋转加载动画
ReentrantReadWriteLock详解
How to analyze the weekly activity rate?
一个文件管理系统的软硬件配置清单
opencv 读取和写入路径有汉字的处理方法
高可用版 主数据库数据结构改变 备数据库会自动改变吗
深入浅出Flask PIN
Fortinet产品导入AWS AMI操作文档
MATLAB gcf figure save image with black background/transparent background
请问下阿里云全托管flink能执行两条flink sql命令么?
spark入门学习-2
How to start an NFT collection