简体   繁体   中英

Mysql: find number of rows which have same value one-after-other

Let say i have table

id|val
1 |1
2 |1
3 |2
4 |5
5 |2
6 |2
7 |2

How to get table like this:

2 | 1 |2
3 | 2 |1
4 | 5 |1
7 | 2 |3

Ie table in which third column is number of similar values in second column.

Sure i can do that using php or perl code, but i remmember it was posible by using sql variables only.

Oh, I think I figured it out. You care about sequences of values that are adjacent. The first column is the maximum id, the second is the value, and the third is the length.

Yes, you can do this with variables:

select max(id), val, count(*)
from (select t.*,
             (@grp := if(@v = val, @grp,
                         if(@v := val, @grp + 1, @grp + 1)
                        )
             ) as grp
      from yourtable t cross join
           (select @v := -1, @grp := -1) params
      order by id
     ) t
group by grp, val
order by max(id);

A purist might have an issue with this - but I'm a purist, and I don't ...

SELECT MAX(id) max_id
     , val -- or MAX(val) if you like
     , COUNT(*) total
  FROM 
     ( SELECT id
            , val
            , CASE WHEN @prev <> val THEN @i:=@i+1 ELSE @i:=@i END i
            , @prev := val prev 
         FROM yourtable
            , (SELECT @prev:=null, @i:=1) vars 
        ORDER 
           BY id
     ) a
 GROUP 
    BY i;

http://www.sqlfiddle.com/#!9/32d395/16

Oh, it looks quite a lot like the other answer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM