MySQL Group By – Grouping Based on Column Consecutive Values

group byMySQL

I have table with let say the below 3 columns

Date                    OfferId         Title   
4/29/16 - 5/19/16       123             title1
5/20/16 - 5/30/16       123             title2
5/31/16 - 6/2/16        123             title3
6/03/16 - 6/13/16       123             title1
6/14/16 - 6/16/16       123             title4
6/17/16 - 6/20/16       123             title2
6/21/16 - 6/25/16       123             title4

i have some other columns which need sum

Where i put range like this 4/29/16 – 5/19/16 it means i have multiple rows for those dates with the same title.

as you can see the

title1 is same between 4/29/16 - 5/19/16 and 6/03/16 - 6/13/16 
title2 is same between 5/20/16 - 5/30/16 and 6/17/16 - 6/20/16
title4 is same between 6/14/16 - 6/16/16 and 6/21/16 - 6/25/16

So when we do grouping on Title so what it does is return 4 results

select Min(Date),OfferId, Title from temp group by Title;

using the above query the results will be

Min(Date)   OfferId         Title   
4/29/16     123             title1
5/20/16     123             title2
5/31/16     123             title3
5/31/16     123             title4

what i wanted is it should be look like this so i can see all the history the title got changed.

Min(Date)   OfferId         Title   
4/29/16     123             title1
5/20/16     123             title2
5/31/16     123             title3
6/03/16     123             title1
6/14/16     123             title4
6/17/16     123             title2
6/21/16     123             title4

How can I achive this

Best Answer

SELECT (@prev = Title) AS same,
       Title,
       `Date`,
       @prev := Title AS t
    FROM ( SELECT @prev := '' ) AS Init
    JOIN ( SELECT `Date`, Title FROM tbl ORDER BY `Date` LIMIT 999999 ) AS x
    HAVING same = 0

See if that gets the right info, plus some junk. Then get rid of the junk:

SELECT `Date`, Title
    FROM ( the entire query above ) AS y
    ORDER BY `Date`