How to escape one or more consecutive rows from table, inoutMode either 1 or 0

情到浓时终转凉″ 提交于 2019-12-07 07:24:24

You could use windowed functions:

WITH cte AS (
  select * ,SUM(CASE WHEN InOutMode=1 THEN 0 ELSE 1 END) -- SUM(1-InOutMode)
            OVER(PARTITION BY EmpCode ORDER BY ID) s
  from test1
), cte2 AS (
  SELECT *, ROW_NUMBER() OVER(PARTITION BY EmpCode, s ORDER BY id) as rn
  FROM cte 
), cte3 AS (
   SELECT *, MAX(rn) OVER(PARTITION BY EmpCode, s) AS m
   FROM cte2
)
DELETE FROM cte3
WHERE rn > 1 AND rn <> m;

SELECT *
FROM test1;

Rextester Demo

Intermediate result to illustrate idea (flip-flop):

If you need you could add futher partitions (for example by day).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!