获得最大序列

问题描述

+----+-------+
| id | value | 
+----+-------+
|  1 |    A  |
|  2 |    B  |
|  3 |    C  |
|  4 |    D  |
|  5 |    D  |
|  6 |    D  |
|  7 |    N  |
|  8 |    P  |
|  9 |    P  |
+----+-------+

所需的输出

+----+-------+---------------------+
| id | value |      calc ↓         |
+----+-------+---------------------+
|  1 |    A  |          1          |
|  2 |    B  |          2          |
|  3 |    C  |          3          |
|  4 |    D  |          6          |
|  5 |    D  |          6          |
|  6 |    D  |          6          |
|  7 |    N  |          7          |
|  8 |    P  |          9          |
|  9 |    P  |          9          |
| 10 |    D  |          11         |
| 11 |    D  |          11         |
| 12 |    Z  |          12         |
+----+-------+---------------------+

您能帮我解决这个问题吗? id是身份,输出中必须存在id,输出中必须具有相同的9行。

新注释:我添加了10、11、12行。请注意,具有字母“ D”的ID 10和11与ID 4,5,6处于不同的组

谢谢

解决方法

对于此采样日期,您需要MAX()窗口函数:

SELECT id,value,MAX(id) OVER (PARTITION BY value) calc
FROM tablename
,

如果分组还取决于周围的id,那么这将变成类似间隙和孤岛的问题https://www.red-gate.com/simple-talk/sql/t-sql-programming/the-sql-of-gaps-and-islands-in-sequences/#:~:text=The%20SQL%20of%20Gaps%20and%20Islands%20in%20Sequences,...%204%20Performance%20Comparison%20of%20Gaps%20Solutions.%20

您可以使用Tabibitosan方法https://rwijk.blogspot.com/2014/01/tabibitosan.html

在这里,您还需要按“值”列进行分组,但这并不会使其复杂化:

select id,max(id) over (partition by value,island) calc
from (
select id,id - row_number() over(partition by value order by id) island
from my_table
) as sq
order by id;

id - row_number() over(partition by value order by id)表达式为您提供一个数字,每当ID值对每个值的值变化大于1时,该数字都会变化。这将包含在max(id) over (partition by value,island)表达式中。岛号仅对该特定值有效。在您的情况下,值N和D的计算出的孤岛数均为6,但需要区别对待。

Db小提琴https://www.db-fiddle.com/f/jahP7T6xBt3cpbLRhZZdQG/1

,
Text ='"+textBox3.Text + "where