首页 > 解决方案 > 查找连续字段,直到字段更改并将序列号添加到具有相同名称的行

问题描述

这建立在这个问题之上:Find contiguous index until certain field changes

基本上有看起来像这样的数据

Name    Address Index
-----   ------- --
Test    0x0100  0
Test    0x0100  1
Test    0x0100  2
Test    0x0100  3
Test    0x0100  4
Test2   0x0100  5
Test2   0x0100  6
Test2   0x0100  7
Test    0x0100  8
Test    0x0100  9
Test    0x0100  10
Test3   0x0100  11
Test3   0x0100  12
Test    0x0100  13
Test    0x0100  14
Test    0x0100  15

数据按地址排序,然后索引。

然后根据我上一个问题的答案进行如下总结:

Name    Address Start   End
-----   ------- -----   ----
Test    0x0100  0       4
Test2   0x0100  5       7
Test    0x0100  8       10
Test3   0x0100  11      12
Test    0x0100  13      15

我现在想做的是在相同地址空间内具有相同值的那些名称的末尾附加一个序列号,所以是这样的:

Name    Address Start   End
-----   ------- -----   ----
Test_1    0x0100  0       4
Test2     0x0100  5       7
Test_2    0x0100  8       10
Test3     0x0100  11      12
Test_3    0x0100  13      15

这对 MySQL 可行吗?存储过程没问题。

谢谢!

标签: mysqlsql

解决方案


这是一个差距和孤岛问题。您可以使用不同的行号来获取组。

但是,如果您已经拥有数据,那么:

select (case when count(*) over (partition by name) = 1 then name
             else concat(name, '_', row_number() over (partition by name order by start))
        end) as name,
       . . .
from (<your query that does the first part here>) t;

窗口函数从 MySQL 8.0 开始可用。


推荐阅读