我们在客户表中有两列,其中包含客户 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/