sql条件行号重置

2ic8powd  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(354)

假设我有以下用户操作。我正在寻找一个最古老的不间断行动接受文件类型xx。
删除操作将考虑中断
如果用户已接受xx,但随后接受a。这将是一次中断。
我实际上是寻找班轮行动接受xx,但它必须是最古老的,每当有删除,我们需要重置基线。
t11是预期结果。

EVENTTIME    ACTION      DOCUMENTTYPE   
--------------------------------------
T1           Accept      A
T2           Accept      XX
T3           Delete      XX
T4           Accept      A
T5           Accept      XX
T6           Accept      XX
T7           Delete      XX
T8           Accept      A
T9           Accept      XX
T10          Accept      A
T11          Accept      XX
T12          Accept      XX
T13          Accept      XX

笔记:
t2不是结果,因为t3中断了时间线。
t5不是结果,因为t7中断了时间线。
t9不是结果,因为t10接受一个中断,而xx接受一个中断。
t11是因为在上述时间线重置之后的结果。这是对xx最古老的接受。
我想行数加上额外的分组(累计和)查询解决方案。有什么想法吗?

wqlqzqxt

wqlqzqxt1#

一种方法使用 not exists :

select min(eventtime)
from t
where not exists (select 1
                  from t t2
                  where t2.eventtime > t.eventtime and t2.DOCUMENTTYPE <> 'XX'
                 );

另一个有趣的方法是使用窗口函数:

select min(eventtime)
from (select t.*,
             row_number() over (order by eventtime desc) as seqnum,
             row_number() over (partition by documenttype order by eventtime desc) as seqnum_dt
      from t
     ) t
where documenttype = 'XX' and
      seqnum = seqnum_dt;

这使用了这样一个事实,即 'XX' 仅基于 eventtime 或者基于 eventtime 当按分区时 dcoumenttype .

68bkxrlz

68bkxrlz2#

这将返回最后一组accept/xx行的第一行:

WITH flag_actions AS
 (
   SELECT t.*
     -- used to filter in next step: previous row was not Accept/XX = 1st row of group
     ,Lag(CASE WHEN ACTION = 'Accept' AND DOCUMENTTYPE = 'XX' THEN 0 ELSE 1 END, 1, 1)
      Over (PARTITION BY ???
            ORDER BY EVENTTIME) AS flag
   FROM t
 )
,find_latest AS
 (
   SELECT flag_actions.*
      -- used to filter in next step
     ,Row_Number()
      Over (PARTITION BY ??? 
            ORDER BY EVENTTIME DESC) AS rn
   FROM flag_actions
   WHERE ACTION = 'Accept' -- last row for each group of Accept/XX rows
     AND DOCUMENTTYPE = 'XX'
     AND flag = 1
 )
SELECT * 
FROM find_latest
WHERE rn = 1

如果没有嵌套的olap函数,我怀疑你能得到这样的结果。

相关问题