Mysql:找到一个接一个具有相同值的行数

时间:2016-03-04 17:35:18

标签: mysql sql

假设我有桌子

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

如何获得这样的表:

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

即表格,其中第三列是第二列中类似值的数量。

当然我可以使用php或perl代码来做到这一点,但我通过仅使用sql变量来重新构建它。

2 个答案:

答案 0 :(得分:2)

哦,我想我明白了。您关心的是相邻值的序列。第一列是最大值,第二列是值,第三列是长度。

是的,您可以使用变量执行此操作:

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);

答案 1 :(得分:0)

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