对行进行计数,其中行中的值也在前一行中

问题描述 投票:0回答:2

我想获得一个计数,其中一行中值的内容也位于前一行中。

   Row | Item1 | Item2 | Item 3 |
   1   | Dog   | Cat   | Rat
   2   | Bird  | Cat   | Horse
   3   | Horse | Dog   | Rat
   4   | Bird  | Cat   | Horse
   5   | Horse | Bird  | Cat

第2行会增加Cat的数量,因为Cat在第1和2行中

第3行会增加Horse的数量,因为Horse也在第2行中

第4行会增加Horse的数量,因为Horse也在第3行中

第5行会增加Horse AND Cat的数量,因为这两个都出现在第4行中。

最多可以有100个项目或SKU,我可以在任何或所有字段上建立索引。在任何给定时间,可能有1000到2000行。

除了“ SELECT * FROM table WHERE”之外,我什至无法绕开此查询的起点

mysql sql select count gaps-and-islands
2个回答
0
投票

这可以通过窗口函数来完成(在MySQL 8.0中可用。)>

一种选择是取消显示结果集,然后使用lag()检查以前的记录。假设id总是以1递增,则可以执行以下操作:

select
    item,
    sum(case when id = lag_id + 1 then 1 else 0 end) cnt_consecutive
from (
    select
        t.*,
        lag(id) over(partition by item order by id) lag_id
    from (
        select id, item1 item from mytable
        union all select id, item2 from mytable
        union all select id, item3 from mytable
    ) t
) t
group by item
order by item

如果您没有递增的列,则可以使用dense_rank()生成一列:

select
    item,
    sum(case when new_id = lag_new_id + 1 then 1 else 0 end) cnt_consecutive
from (
    select 
        t.*,
        lag(new_id) over(partition by item order by new_id) lag_new_id
    from (
        select
            t.*,        
            dense_rank() over(order by id) new_id
        from (
            select id, item1 item from mytable
            union all select id, item2 from mytable
            union all select id, item3 from mytable
        ) t
    ) t
) t
group by item
order by item

this DB Fiddle

中,两个查询均返回:
项目| cnt_连续:---- | --------------:鸟| 1个猫| 2狗| 0马| 3老鼠0

0
投票

首先,创建具有SKU所有可用唯一值的表:

© www.soinside.com 2019 - 2024. All rights reserved.