星点xingdian 2021-01-20 00:01 采纳率: 0%
浏览 82
已结题

通过sql获取该公司在第a天的收盘价,最近的一个收盘价作为第a天的收盘价。

 

StockPrice Table

 

price_date

price

 

2019-09-25

23.23

 

2019-09-26

32.54

 

2019-09-27

34.55

 

2019-09-28

null

 

2019-09-29

null

 

2019-09-30

54.22

 

2019-10-01

null

 

2019-10-02

null

 

2019-10-03

null

 

2019-10-04

null

 

2019-10-05

null

 

2019-10-06

null

 

2019-10-07

null

 

2019-10-08

33.80

 

2019-10-09

33.83

 


上表节选自某上市公司股票每日收盘价记录,适逢股市休市或该股停牌,则无收盘价记录,于表中记为null。
 
现需通过sql获取该公司在第a天的收盘价,若第a天无收盘价记录,则取该日之前,最近的一个收盘价作为第a天的收盘价。(例如,2019-10-05的收盘价取2019-09-30的54.22)
select
  price_date,
        price,
        max(newprice) over (partition by num) close_price
from
(
    select
        price_date,
        price,
        newprice,
        sum(c) over ( UNBOUNDED PRECEDING) num
    from
        (
    select
        price_date,
        price,
        if(price = null,0,price) newprice,
        if(price = null,0,1) c
    from
        `StockPrice Table` 
        ) t1
)t2
改了下让求距离该日期最近的,就是说可以向前取也可以向后取,说如果求最近得价格,如果为null,就向前一天和后一天找,如果找到一个不为null且距离该日期最近的,比如:2019.5.12为null,2019.5.10是32.2,2019.5.13是23.0,那2019.5.12就是23.0.因为对于5.12来说5.13比5.10近

这个需求改变了,怎么改SQL?
 

  • 写回答

4条回答 默认 最新

  • bj_0163_bj 2021-01-20 09:21
    关注
    select t3.price_date,d.price
    from (
    select t.price_date,case when datediff(price_date,price_date2)>datediff(price_date3,price_date) then price_date3 else price_date2 end price_date4
    from (
    select t.price_date,t.price_date2,min(c.price_date) price_date3
    from (
    select a.price_date,max(b.price_date) price_date2
    from `StockPrice Table`  a
    left join (select * from `StockPrice Table`  where a.price is not null) b 
    on a.price_date>=b.price_date
    group by a.price_date
    ) t
    left join (select * from `StockPrice Table`  where a.price is not null) c
    on t.price_date<=c.price_date
    group by t.price_date,t.price_date2
    ) t2 ) t3
    join `StockPrice Table`  d 
    on t3.price_date4=d.price_date
    
    --日期间隔函数不同sql 会有不同
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码