Home > Database > Mysql Tutorial > How to Count Consecutive Occurrences of Values in a SQL Table?

How to Count Consecutive Occurrences of Values in a SQL Table?

Barbara Streisand
Release: 2025-01-05 15:40:40
Original
177 people have browsed it

How to Count Consecutive Occurrences of Values in a SQL Table?

Grouping Values based on Consecutive Occurrences

To count consecutive occurrences of values in a table, an effective approach is to calculate the difference in row numbers.

Consider the following query:

select name, count(*) 
from (
    select t.*,
           (row_number() over (order by id) -
            row_number() over (partition by name order by id)
           ) as grp
    from t
) t
group by grp, name;
Copy after login

This subquery generates two row numbers for each row:

  • row_number() over (order by id): A sequential number based on the overall row order.
  • row_number() over (partition by name order by id): A sequential number specific to each unique name.

By subtracting the two row numbers, we create a "group" identifier (grp) that increments whenever the name changes or there is a distinct consecutive occurrence of the same name.

The final query then groups the rows based on this grp and counts the occurrences of each name within each group. This results in the desired count of consecutive occurrences:

+------+------------+
| Name | Repetition |
+------+------------+
| A    |          2 |
| B    |          4 |
| C    |          1 |
| B    |          2 |
+------+------------+
Copy after login

This approach provides an efficient way to identify consecutive values in a table by leveraging the difference in row numbers as a grouping mechanism.

The above is the detailed content of How to Count Consecutive Occurrences of Values in a SQL Table?. 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