MySQL: Count of records with consecutive months

后端 未结 2 498
轮回少年
轮回少年 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:26

    I used this StackOverflow answer for guidance (Check for x consecutive days - given timestamps in database)

    SELECT a.person, COUNT(1) AS consecutive_months
    FROM
    (
    
      SELECT a.person, IF(b.YearMonth IS NULL, @val:=@val+1, @val) AS consec_set
      FROM (
        SELECT DISTINCT person, EXTRACT(YEAR_MONTH from purdate) as YearMonth from records
        ) a
      CROSS JOIN (SELECT @val:=0) var_init
      LEFT JOIN (SELECT DISTINCT person, EXTRACT(YEAR_MONTH from purdate) as YearMonth from records) b ON
          a.person = b.person AND
          a.YearMonth = b.YearMonth + 1
       ) a
    GROUP BY a.consec_set
    HAVING COUNT(1) >= 2    
    

    Here is the SQLFiddle - http://sqlfiddle.com/#!2/cc5c3/55

提交回复
热议问题