Home > Database > Mysql Tutorial > How to Find Minimum and Maximum Start and End Times for Consecutive Rows within Activity Groups?

How to Find Minimum and Maximum Start and End Times for Consecutive Rows within Activity Groups?

Susan Sarandon
Release: 2025-01-03 01:03:39
Original
681 people have browsed it

How to Find Minimum and Maximum Start and End Times for Consecutive Rows within Activity Groups?

Finding Minimum and Maximum Values for Consecutive Rows

You have a dataset with rows representing activities, grouped by name and ordered by row number. The goal is to find the minimum and maximum values of start and end times for consecutive rows within each activity group.

Solution Using Row Number Difference:

One approach is to use the difference between row numbers to identify consecutive rows of the same activity:

with cte as (
  select *,
    row_number() over (partition by name order by rn) as seqnum_n,
    row_number() over (partition by name, act order by rn) as seqnum_na
  from input
)
select name, act, min(startt), max(endd)
from cte
group by seqnum_n - seqnum_na, name, act;
Copy after login

Explanation:

  1. Create a common table expression (CTE) called cte by adding two additional columns:

    • seqnum_n: Row number within each name group.
    • seqnum_na: Row number within each name-activity group.
  2. Calculate the difference between seqnum_n and seqnum_na. Consecutive rows within each activity have the same difference value.
  3. group by the difference value, name, and activity to aggregate the minimum and maximum values.

The above is the detailed content of How to Find Minimum and Maximum Start and End Times for Consecutive Rows within Activity Groups?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template