窗口函数

本文通过具体案例展示了如何使用SQL中的窗口函数来计算累积和及移动平均值等统计数据,包括sum(), avg()等函数的运用,并介绍了first_value()与last_value()函数的应用场景。

为计算一定的范围的累积和移动平均值,可以结合聚合函数使用:sum() avg() max() min() count() variance() stddev() 

first_value() last_value()结合使用。

select 
t.prd_type_id
,t.amount
,t.month
,sum(t.amount) over(order by t.prd_type_id desc rows between UNBOUNDED PRECEDING AND CURRENT ROW) AS cumulative_amount
 from all_sales t
where t.year=2003
and t.month =1
and t.amount is not null
and t.emp_id=21
order by t.prd_type_id desc
============================
1	4	3034.84	1	3034.84
2	3	1034.84	1	4069.68
3	2	1034.84	1	5104.52
4	1	10034.84	1	15139.36

 

 

select 
t.prd_type_id
,t.amount
,t.month
,avg(t.amount) over(order by t.prd_type_id desc rows between 3 PRECEDING AND current row) AS cumulative_amount
 from all_sales t
where t.year=2003
and t.month =1
and t.amount is not null
and t.emp_id=21
order by t.prd_type_id desc
=========================
1	4	3034.84	1	3034.84
2	3	1034.84	1	2034.84
3	2	1034.84	1	1701.50666666667
4	1	10034.84	1	3784.84

 

select 
t.prd_type_id
,t.amount
,t.month
,avg(t.amount) over(order by t.prd_type_id desc rows between 1 PRECEDING AND 1 following) AS cumulative_amount
 from all_sales t
where t.year=2003
and t.month =1
and t.amount is not null
and t.emp_id=21
order by t.prd_type_id desc
=====================
1	4	3034.84	1	2034.84
2	3	1034.84	1	1701.50666666667
3	2	1034.84	1	4034.84
4	1	10034.84	1	5534.84

 

select 
t.prd_type_id
,t.amount
,t.month
,first_value(t.amount) over(order by t.prd_type_id desc rows between 1 PRECEDING AND 1 following) AS cumulative_amount
,last_value(t.amount) over(order by t.prd_type_id desc rows between 1 PRECEDING AND 1 following) AS cumulative_amount
 from all_sales t
where t.year=2003
and t.month =1
and t.amount is not null
and t.emp_id=21
order by t.prd_type_id desc
==========================
1	4	3034.84	1	3034.84	1034.84
2	3	1034.84	1	3034.84	1034.84
3	2	1034.84	1	1034.84	10034.84
4	1	10034.84	1	1034.84	10034.84

  

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值