SQL序列根据条件增加/重置

时间:2014-08-13 14:35:33

标签: sql sequence vertica

我正在尝试在SQL中编写一个查询但是已经遇到了问题。

我的结果表类似于以下内容:

Category    Date
1234    15/07/2014
1234    17/07/2014
1234    29/07/2014
1234    31/07/2014
1234    02/08/2014
1234    04/08/2014
1234    06/08/2014
1211    17/07/2014
1211    06/08/2014
1211    08/08/2014

我正在尝试创建一个序列,当日期差异大于2时,该序列会重置,以及该类别的唯一性如下:

Category    Date    Sequence
1234    15/07/2014  1
1234    17/07/2014  2
1234    29/07/2014  1
1234    31/07/2014  2
1234    02/08/2014  3
1234    04/08/2014  4
1234    06/08/2014  5
1211    17/07/2014  1
1211    06/08/2014  1
1211    08/08/2014  2

1 个答案:

答案 0 :(得分:0)

这可以使用CONDITIONAL_TRUE_EVENT功能完成。感谢sKwa & scutter的帮助!

SELECT Category, 
       Date, 
       RANK() 
         OVER ( 
           PARTITION BY Category, seq 
           ORDER BY Date) 
FROM   (SELECT Category, 
               Date, 
               CONDITIONAL_TRUE_EVENT(DATEDIFF(day, prev_Date, Date) > 2) 
                 OVER ( 
                   PARTITION BY Category 
                   ORDER BY Date) AS seq 
        FROM   (SELECT *, 
                       LAG(Date, 1) 
                         OVER ( 
                           PARTITION BY Category 
                           ORDER BY Date) prev_Date 
                FROM   test) q) q2 
ORDER  BY Category, 
          Date;