WITH C1 AS (
SELECT *,
CASE
WHEN start_time <= MAX(IFnull(end_time,'9999-12-31 00:00:00.000')) OVER(
partition by id
ORDER BY start_time
ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING
)
THEN 0
ELSE 1
END AS isstart
FROM activity
)
SELECT ID,start_time,end_time,
SUM(isstart) OVER(partition by id ORDER BY ID ROWS UNBOUNDED PRECEDING) AS DG
FROM C1;
Điều này sẽ hiệu quả với bạn