前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >波峰波谷sql

波峰波谷sql

作者头像
chimchim
发布2022-11-13 13:14:54
2860
发布2022-11-13 13:14:54
举报
文章被收录于专栏:chimchim要努力变强啊

目录

波峰波谷定义

准备数据

计算方法 


波峰波谷定义

波峰:当天的价格大于前一天和后一天

波谷:当天的价格小于前一天和后一天

准备数据

代码语言:javascript
复制
CREATE TABLE syc_ads.t1
(
UID string,
DT string,
Price double
);

Insert into syc_ads.t1
VALUES
('00001','2014-06-01',-20),
('00001','2014-06-02',50),
('00001','2014-06-04',15),
('00001','2014-06-05',13),
('00001','2014-06-06',100),
('00002','2014-06-02',33),
('00002','2014-06-05',66),
('00002','2014-06-06',101),
('00002','2014-06-07',26),
('00002','2014-06-08',30),
('00002','2014-06-10',43)

计算方法 

代码语言:javascript
复制
方法1:
with t as
(select *,row_number() over(partition by UID order by DT) as rn
 from syc_ads.t1)
select 
     a.UID
    ,a.DT
    ,a.Price
    ,case when (b.rn is null and c.Price>a.Price)
                 or (c.rn is null and b.Price>a.Price)
                 or (b.Price>a.Price and c.Price>a.Price)
            then '波谷'
          when (b.rn is null and c.Price<a.Price)
                 or (c.rn is null and b.Price<a.Price)
                 or (b.Price<a.Price and c.Price<a.Price)
            then '波峰' 
          else '' 
    end as Wave  
 from t a
 left join t b on a.UID=b.UID and a.rn=b.rn+1 
 left join t c on a.UID=c.UID and a.rn=c.rn-1 
 order by a.UID,a.rn

方法2:
select
	UID,DT,Price
	,case when Price > lag_price and Price > lead_price then '波峰'
	      when Price < lag_price and Price < lead_price then '波谷'
	      else '其他' end as price_type
from(
	select
		 UID
        ,DT
		,Price
        ,lag(Price,1) over(partition by UID order by DT) as lag_price
		,lead(Price,1) over(partition by UID order by DT) as lead_price
	from syc_ads.t1
) t
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-06-21,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 波峰波谷定义
  • 准备数据
  • 计算方法 
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档