Grouping similar rows next to each other in MySQL

后端 未结 1 546
遇见更好的自我
遇见更好的自我 2021-01-17 05:47

I have no idea how to explain this well, so please bear with me.

I am trying to group similar rows that are right next to each other, essentially ignoring the n+1th

相关标签:
1条回答
  • 2021-01-17 06:16

    You can do this by using a clever trick. The trick is to count the number of descriptions up to a particular id that are different from the description at that id. For values in a sequence, this number will be the same.

    In MySQL you can do this count using a correlated subquery. The rest is just grouping by this field to bring the values together:

    select min(id) as id, description, count(*) as numCondensed
    from (select t.*,
                 (select count(*)
                  from table t2
                  where t2.id <= t.id and t2.description <> t.description
                 ) as grp
          from table t
         ) t
    group by description, grp;
    
    0 讨论(0)
提交回复
热议问题