下面是我在SQL中想要的数据和输出的示例.
<表类>
id
日期
标记
tbody><<tr>2022-04-05 0 2022-04-06 1 2022-04-07 1 2022-04-08 1 2022-04-09 0 2022-04-10 0 2022-04-11 1 2022-04-12 1 2022-04-13 1 2022-04-14 1 2022-04-15 0 2022-04-16 0 b2022-04-05 0 b2022-04-06 1 b2022-04-07 1 b2022-04-08 0 表类>
这是一个缺口和孤岛问题。一种方法使用行数差异方法:
WITH cte AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY id ORDER BY date) rn1,
ROW_NUMBER() OVER (PARTITION BY id, flag ORDER BY date) rn2
FROM yourTable
)
SELECT id, date, flag,
SUM(flag) OVER (PARTITION BY id, flag, rn1 - rn2 ORDER BY date) AS count
FROM cte
ORDER BY id, date;