How to group continuous ranges using MySQL

前端 未结 3 1384
温柔的废话
温柔的废话 2020-12-03 22:29

I have a table that contains categories, dates and rates. Each category can have different rates for different dates, one category can have only one rate at a given date.

3条回答
  •  失恋的感觉
    2020-12-03 23:04

    MySQL doesn't support analytic functions, but you can emulate such behaviour with user-defined variables:

    SELECT   CatID, Begin, MAX(Date) AS End, Rate
    FROM (
      SELECT   my_table.*,
               @f:=CONVERT(
                 IF(@c<=>CatId AND @r<=>Rate AND DATEDIFF(Date, @d)=1, @f, Date), DATE
               ) AS Begin,
               @c:=CatId, @d:=Date, @r:=Rate
      FROM     my_table JOIN (SELECT @c:=NULL) AS init
      ORDER BY CatId, Rate, Date
    ) AS t
    GROUP BY CatID, Begin, Rate
    

    See it on sqlfiddle.

提交回复
热议问题