我有一个示例SQL表,其中包含以下示例数据:
Step | Member
---------------
100 | A
100 | B
200 | C
200 | A
500 | C
500 | A
500 | D
800 | D
800 | B
我需要从所有下一个连续步骤中删除用户。 如上表所示:
最终结果如下:
Step | Member
---------------
100 | A
100 | B
200 | C
500 | D
800 | B
使用SQL
查询以任何方式执行此操作?
答案 0 :(得分:3)
试试这个:
;with cte as(select *,
dense_rank() over(order by step) dr,
row_number() over(partition by member order by step) rn
from t)
select member, min(step) as step
from cte
group by member, dr - rn
点子:
Step | Member | dr | rn | dr - rn
----------------------------------------
100 | A 1 1 0
100 | B 1 1 0
200 | C 2 1 1
200 | A 2 2 0
500 | C 3 2 1
500 | A 3 3 0
500 | D 3 1 2
800 | D 4 2 2
800 | B 4 2 2
按最后一栏和成员分组,我认为可以得到您想要的结果。现在不能在小提琴中检查。
答案 1 :(得分:1)
在玩完之后,在这里看到类似的问题,我就去了它
SELECT step, member
FROM (
SELECT s1.step, s1.member,
(SELECT MAX(step) FROM @steps WHERE step < s1.step) as prevStep,
(SELECT MAX(step) FROM @steps WHERE step < s1.step AND member = s1.member) as memberPrevStep
FROM @steps as s1
) AS s2
WHERE memberPrevStep IS NULL OR prevStep <> memberPrevStep
这可能是一个可接受的解决方案还是有更好的方法?