在SQL Server 2012+:
在common table expression使用窗函數lag()
得到datediff()
相比,createdat_local
以前的行值,然後有條件聚集sum() over()
生成排名:
;with cte as (
select *
, datediff(minute,lag(createdat_local) over (
partition by user_id
order by createdat_local
),createdat_local) as prev_dat
from t
)
select user_id, ride_id, createdat_local
, sum(case when coalesce(prev_dat,16)>15 then 1 else 0 end) over (
partition by user_id
order by createdat_local
) as rank
from cte
rextester演示:http://rextester.com/EQUC48356
回報:
+---------+----------+---------------------+------+
| user_id | ride_id | createdat_local | rank |
+---------+----------+---------------------+------+
| 2681233 | 96783742 | 2017-10-04 06:10:32 | 1 |
| 2681233 | 96784171 | 2017-10-04 06:12:38 | 1 |
| 2681233 | 96924751 | 2017-10-04 13:36:44 | 2 |
| 2681233 | 96925561 | 2017-10-04 13:40:41 | 2 |
| 2681233 | 96926560 | 2017-10-04 13:44:47 | 2 |
| 2681233 | 96994651 | 2017-10-04 18:12:29 | 3 |
| 2681233 | 96995953 | 2017-10-04 18:18:16 | 3 |
| 2681233 | 96996937 | 2017-10-04 18:22:15 | 3 |
| 2681233 | 96997195 | 2017-10-04 18:24:00 | 3 |
+---------+----------+---------------------+------+
你正在使用哪個dbms?不要標記不涉及的產品。 – jarlh
是sql-server還是postgresql? –
我刪除了不兼容的數據庫類型。請僅使用您真正使用的數據庫進行標記。 –