mysql - mysql中如何统计连续的重复行

标签 mysql sql

我们在客户表中有两列,其中包含客户 ID 和服务 ID。因此,对于每个使用多项服务的客户,我们必须找到客户使用的连续服务的最大数量。

create table customer(id int not null auto_increment,customerid varchar(20), serviceid varchar(20),primary key(id));

insert into customer(customerid,serviceid) values('Nitesh','Mobile');
insert into customer(customerid,serviceid) values('Nitesh','Mobile');
insert into customer(customerid,serviceid) values('Nitesh','Landline');
insert into customer(customerid,serviceid) values('Nitesh','Broadband');
insert into customer(customerid,serviceid) values('Nitesh','Mobile');

insert into customer(customerid,serviceid) values('Nishant','Mobile');
insert into customer(customerid,serviceid) values('Nishant','Landline');
insert into customer(customerid,serviceid) values('Nishant','Landline');
insert into customer(customerid,serviceid) values('Nishant','Landline');
insert into customer(customerid,serviceid) values('Nishant','Broadband');

insert into customer(customerid,serviceid) values('Soe','Mobile');
insert into customer(customerid,serviceid) values('Soe','Mobile');
insert into customer(customerid,serviceid) values('Soe','Landline');
insert into customer(customerid,serviceid) values('Soe','Broadband');
insert into customer(customerid,serviceid) values('Soe','Mobile');

我必须统计客户连续使用的最大服务。

输出:

Customerid|Serviceid|ServiceidCount
----------------------------------

Nitesh|Mobile|2
Nishant|Landline|3
Soe|Mobile|2

最佳答案

假设您有一个指定顺序的列,例如 id

然后你可以使用变量来做到这一点:

select customer, max(rn) as serviceidcnt,
       substring_index(group_concat(serviceid order by rn desc)) as serviceid
from (select c.*,
             (@rn := if(@cs = concat_ws(':', customerid, serviceid), @rn + 1,
                        if(@cs := concat_ws(':', customerid, serviceid), 1, 1)
                       )
             ) as rn
      from customer c cross join
           (select @rn := 0, @cs := '') params
      order by c.customer, ??
     ) cs
group by customer;

?? 是用于排序的列。

注意:获取服务 ID 需要使用依赖于 group_concat() 的 MySQL“hack”。默认情况下,这限制为大约 1000 字节的内部缓冲区大小。这可以更改。

关于mysql - mysql中如何统计连续的重复行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46445585/

相关文章:

java - 将 SQL 连接传递给 ActionListener(线程)

mysql - 无法使用 case 且存在于 sql 语句中

c# - 检查列是否允许空值,C#?

php - 带有数据库的 Codeigniter 下拉菜单

mysql - 缓冲池使用百分比查询返回无效结果

Mysql 连接器无法创建具有复合主键的表

mysql - 错误 1064 : SQL syntax

mysql - 筛选 Node.js、Express 和 mysql 模块

php - 数据库中的复杂关系(使用 Laravel)

mysql - 查询以使用键和至少一个好行为行填充缺失的非规范化列值?