如何return前行值与SQLtable中的列条件?

How to return preceding row value with column condition in SQL table?

我有以下 SQL table,其中仅当条件类型为 00 时我才需要最新价格:

ProductID ConditionType Date        Price
00001          01        2018-01-01  4.00 
00001          01        2018-01-08  5.00   
00001          00        2018-01-09  4.50  
00001          01        2018-01-22  6.00  
00001          00        2018-01-29  3.00  

我试过使用滞后函数,但分区有问题。

select 
ProductID,ConditionType,Date,Price
,
case when conditiontype = 0 then
lag(Price,1) over (partition by ProductID,ConditionType order by Date asc)
else Price 
end as lag
from TABLE

查询输出:

ProductID ConditionType Date        Price  Lag
00001          01        2018-01-01  4.00  4.00
00001          01        2018-01-08  5.00  5.00 
00001          00        2018-01-09  4.50  null
00001          01        2018-01-22  6.00  6.00
00001          00        2018-01-29  3.00  4.50

理想情况下,我们希望撤回条件类型为 01 的最后价格,但我无法使其正常工作。

期望的输出:

ProductID ConditionType Date        Price  Lag
00001          01        2018-01-01  4.00  4.00
00001          01        2018-01-08  5.00  5.00 
00001          00        2018-01-09  4.50  5.00
00001          01        2018-01-22  6.00  6.00
00001          00        2018-01-29  3.00  6.00

lag()中只需要一个分区子句:

select ProductID, ConditionType, Date, Price,
       (case when conditiontype = '00' 
             then lag(Price) over (partition by ProductID order by Date)
             else Price 
        end) as Lag
from TABLE;

您可以使用 first_value() 并忽略 NULL 值来执行此操作:

select t.*,
       first_value(case when conditionType = '00' then price end ignore nulls) over
           (partition by productId
            order by date desc
           ) as most_recent_00_price
from t;

编辑:

我误解了这个问题。我以为你想要最新的数据。您需要 "running" 最近的值。

SQL 中最简单的方法使用 lag(ignore nulls),但 Impala 不支持。但是你可以使用两个 window 函数:

select t.*,
       max(case when date = date_00 then price end) over (partition by productId) as most_recent_00_price
from (select t.*,
             max(case when conditionType = '00' then date end) over (partition by productId order by date) as date_00
      from t
     ) t