如何找到具有连续值的用户

时间:2017-02-08 19:26:36

标签: sql sql-server

我有一个查询结果如下

Water

我正在寻找连续3次结果为n的用户。在上面的结果中,在此之上的查询应该只给我xxx5516用户 我该怎么做?

3 个答案:

答案 0 :(得分:1)

最简单的方法是使用lag()lead()

select distinct id
from (select t.*, lead(result) over (partition by id order by date) as result_1,
             lead(result, 2) over (partition by id order by date) as result_2
      from t
     ) t
where result = 'n' and result_1 = 'n' and result_2 = 'n'

答案 1 :(得分:0)

使用带有范围参数的窗口函数来检查过去的2个连续结果:

SELECT * from (
SELECT ID, date, result, 
SUM(case when result = 'n' then 1 else 0 end)) 
    OVER (PARTITION BY ID 
            ORDER BY date 
            ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) result_prev_sum
FROM table
) x
WHERE x.result_prev_sum = 3

如果您只想要第三个连续结果,而不是更多,请使用UNBOUNDED PRECEDING而不是BETWEEN 2 PRECEDING AND CURRENT ROW。

答案 2 :(得分:0)

从表中选择不同的ID

其中count(result)= 3;