简体   繁体   English

SQL - 检查前一行,直到找到请求的值

[英]SQL - check previous row until the requested value is found

I've got a dataset like below:我有一个如下数据集:

ID   ReportingDate  Status
123  05/05/2020     GREEN
123  12/05/2020     NONE
123  19/05/2020     NONE
123  26/05/2020     AMBER
123  02/06/2020     RED
123  09/06/2020     NONE
123  16/06/2020     GREEN
123  23/06/2020     NONE
123  30/06/2020     AMBER

I want to ignore the NONE statuses and take the previous value, which may be previous row, but sometimes 2 or 3 rows before.我想忽略 NONE 状态并取之前的值,这可能是前一行,但有时是之前的 2 或 3 行。 Basically the final output should like the column "FINAL"基本上最后的 output 应该像“FINAL”列

ID   ReportingDate  Status   FINAL
123  05/05/2020     GREEN    GREEN 
123  12/05/2020     NONE     GREEN
123  19/05/2020     NONE     GREEN
123  26/05/2020     AMBER    AMBER
123  02/06/2020     RED      RED
123  09/06/2020     NONE     RED
123  16/06/2020     GREEN    GREEN
123  23/06/2020     NONE     GREEN
123  30/06/2020     AMBER    AMBER

I've tried to use LAG() or LEAD() functions, but it doesn't work as requested.我尝试使用 LAG() 或 LEAD() 函数,但它不能按要求工作。

UPPER
(
   CASE 
      WHEN psh.Status = 'NONE'
      THEN LAG(psh.Status,1,psh.Status) OVER
           (
              PARTITION BY psh.ID 
              ORDER BY rp.ReportingDate
           ) 
      ELSE psh.Status 
   END
) AS OverallStatusHistory

Could you advise me, if there is a way how to achieve it, please?你能告诉我,如果有办法如何实现它,好吗?

Many thanks!非常感谢!

You can assign groups based on the count of non- 'NONE' values.您可以根据非'NONE'值的计数来分配组。 Then spread the value:然后传播价值:

select t.*,
       max(nullif(status, 'NONE')) over (partition by id, grp) as imputed_status
from (select t.*,
             sum(case when status = 'NONE' then 0 else 1 end) over (partition by id order by reportingdate) as grp
      from t
     ) t;

Here is a db<>fiddle. 是一个 db<>fiddle。

The SQL standard actually supports the IGNORE NULLS option on LAG() (and various other window functions). SQL 标准实际上支持LAG()上的IGNORE NULLS选项(以及各种其他 window 函数)。 This would make it possible to solve this without a subquery.这样就可以在没有子查询的情况下解决这个问题。 Unfortunately, SQL Server does not (yet???) support that functionality.不幸的是,SQL 服务器不(还???)支持该功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM