简体   繁体   English

MySQL:查找具有相同值的行数

[英]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. 当然我可以使用php或perl代码来做到这一点,但我记得仅通过使用sql变量就可以做到这一点。

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. 第一列是最大ID,第二列是值,第三列是长度。

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 http://www.sqlfiddle.com/#!9/32d395/16

Oh, it looks quite a lot like the other answer 哦,看起来很像其他答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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