如何在SQL表中使用列条件返回前一行值?

问题描述 投票:1回答:2

我有下面的SQL表,其中我只需要条件类型为00时才需要最新的价格。

Table:
        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
Output from query:
        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的最后价格,但我无法使其正常工作。

Desired output:
        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

感谢先进的帮助。

sql case impala
2个回答
2
投票

您可以使用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;

编辑:

我误解了这个问题。我以为你想要最新的数据。你想要“运行”最近的价值。

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

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

1
投票

您只需要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;
© www.soinside.com 2019 - 2024. All rights reserved.