【问题标题】:SQLite Window functions: give NULL result when sufficient window size is not availableSQLite 窗口函数:当没有足够的窗口大小时给出 NULL 结果
【发布时间】:2021-11-26 19:19:40
【问题描述】:
create table boll as select
     *, (avg(close) over win)-2*sqrt((avg(close*close) over win)-pow((avg(close) over win),2)) as BOLD,
     (avg(close) over win)+2*sqrt((avg(close*close) over win)-pow((avg(close) over win),2)) as BOLU
     from bhav
     window win as (partition by isin order by timestamp rows 19 preceding);

使用上述查询,如果当前行之前的行数少于 19 行,是否可以通过窗口 win 的计算返回 NULL

【问题讨论】:

    标签: sql sqlite count average window-functions


    【解决方案1】:

    只需使用LAG 回顾 19 个时间戳:

    create table boll as 
      select *,
      case when lag(timestamp, 19) over (order by timestamp) is not null then
        avg(close) over win) - 2 * sqrt((avg(close*close) over win) - pow((avg(close) over win), 2)
      end as BOLD,
      case when lag(timestamp, 19) over (order by timestamp) is not null then
        avg(close) over win) + 2 * sqrt((avg(close*close) over win) - pow((avg(close) over win), 2) 
      end as BOLU
    from bhav
    window win as (partition by isin order by timestamp rows 19 preceding);
    

    【讨论】:

      【解决方案2】:

      您可以在您定义的窗口上使用COUNT()窗口函数来检查有多少行:

      create table boll as 
      select *, 
             CASE WHEN COUNT(*) OVER win >= 19 THEN (avg(close) over win) - 2 * sqrt((avg(close*close) over win)-pow((avg(close) over win),2)) END as BOLD,
             CASE WHEN COUNT(*) OVER win >= 19 THEN (avg(close) over win)+2*sqrt((avg(close*close) over win)-pow((avg(close) over win),2)) END as BOLU
      from bhav
      window win as (partition by isin order by timestamp rows 19 preceding);
      

      【讨论】:

        猜你喜欢
        • 2014-04-13
        • 1970-01-01
        • 2023-03-29
        • 1970-01-01
        • 1970-01-01
        • 2021-08-22
        • 2020-04-11
        • 2021-12-11
        • 1970-01-01
        相关资源
        最近更新 更多