MySQL: Count of records with consecutive months

后端 未结 2 529
轮回少年
轮回少年 2021-01-12 22:56

I\'ve searched around for this, but all the similar questions and answers are just different enough not to work.

I have a table with the following fields: person, th

2条回答
  •  青春惊慌失措
    2021-01-12 23:40

    You can do this in MySQL using variables (or very complicated correlated subqueries). In other databases, you would use window/analytic functions.

    The logic is:

    1. Get one row per month and person with a purchase.
    2. Use variables to assign each group of consecutive months a "grouping" value.
    3. Aggregate by the person and the "grouping" value.

    Here is a query that has been tested on your SQL Fiddle:

    select person, count(*) as numMonths
    from (select person, ym, @ym, @person,
                 if(@person = person and @ym = ym - 1, @grp, @grp := @grp + 1) as grp,
                 @person := person,
                 @ym := ym
          from (select distinct person, year(purdate)*12+month(purdate) as ym
                from records r
               ) r cross join
               (select @person := '', @ym := 0, @grp := 0) const
          order by 1, 2
         ) pym
    group by person, grp;
    

提交回复
热议问题