+----+-------+
| 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 在不同的组中
感谢
如果分组也取决于周围的id,那么这就变成了类似于间隙和孤岛的问题https://www.red-gate.com/simple-talk/sql/t-sql-programming/the-sql-of-gaps-and-islands-in-sequences/#:~:text=%20SQL%20of%20Gaps%20和%20Islands%20in%20Sequences,…%204%20性能%20比较%20差距%20解决方案。%20
你可以用Tabhibitosan法https://rwijk.blogspot.com/2014/01/tabibitosan.html
在这里,您还需要根据您的值列进行分组,但这不会使其过于复杂:
select id, value, max(id) over (partition by value, island) calc
from (
select id, value, 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
对于这个样本日期,您需要MAX((窗口函数:
SELECT id, value,
MAX(id) OVER (PARTITION BY value) calc
FROM tablename
SELECT id, value, (SELECT max(id) FROM TABLE inner where inner.value = outer.value)
FROM table as outer