如何获得Redshift / Postgresql LAG窗口函数来有选择地排除记录?

时间:2018-08-15 05:43:16

标签: sql postgresql amazon-redshift window-functions

我在Redshift中有此表,并且正在尝试为以下数据集编写查询。对于第3行之类的“续订成功”并以“子成功”开头的项目,我想将它们标记为“ is_first_renewal = true”,但是它们之前可能带有任意数量的“ RENEWAL Failures”在他们成功之前,所以我无法在这种情况下使用窗口函数LAG。

我也无法过滤掉失败,因为我的查询需要这些失败。

id  phone   op      ts              pr  status   result is_first_renewal
1   3345    xxxx    01/01/2018 6:59 0   SUB     SUCCESS 
2   3345    xxxx    28/02/2018 6:59     RENEWAL FAILURE 
3   3345    xxxx    01/03/2018 6:59 20  RENEWAL SUCCESS TRUE
4   3345    xxxx    02/04/2018 6:59 20  RENEWAL SUCCESS FALSE

我当前的查询是这样:

CASE
    WHEN (status = 'RENEWAL' AND result = 'SUCCESS')
         AND ( (last_value(CASE
                               WHEN pr = 0.0 AND result= 'SUCCESS' THEN
                                 TRUE
                           END)) 
                OVER (PARTITION BY phone
                ORDER BY ts ASC 
                ROWS unbounded preceding) = 'SUB' ) THEN
      TRUE
    ELSE 
      FALSE
    END AS is_first_renewal
FROM notifications
WHERE ((charge_status = 'SUCCESS')
       OR (status ='RENEWAL'
           AND result = 'FAILED'))
ORDER BY
         op,
         phone,
         ts;

因此,目标是找到一种方法来使LAG函数忽略那些“失败”项目……直到找到之前的“成功子项目”为止。有什么建议么? 预先感谢。

1 个答案:

答案 0 :(得分:3)

我想到的方法是针对目标应标记为TRUE的个人记录。考虑一下:

WITH cte AS (
    SELECT *,
        ROW_NUMBER() OVER (PARTITION BY phone ORDER BY ts) rn
    FROM notifications n1
    WHERE EXISTS (SELECT 1 FROM notifications n2 WHERE n1.phone = n2.phone AND
                  n2.ts < n1.ts AND n2.status = 'SUB' AND n2.result = 'SUCCESS') AND
          n1.status = 'RENEWAL' AND n1.result = 'SUCCESS'
)

SELECT n1.*,
    CASE WHEN n2.rn = 1 THEN 'TRUE'
         WHEN n2.rn > 1 THEN 'FALSE' END AS is_first_renewal
FROM notifications n1
LEFT JOIN cte n2
    ON n1.phone = n2.phone AND n1.ts = n2.ts;

enter image description here

此查询似乎在下面给出的Postgres演示链接中有效。

Demo