这是使用窗口功能可以完成的方式。首先,我们创建一个CTE,该CTE具有一个标志,指示新的序列已开始,然后从中生成一个对序列号进行计数的标志。最后,我们对每个序列中的行进行计数以获得排名:
WITH cte AS (SELECt `group`, date, color, COALESCE(color = LAG(color) OVER(ORDER BY `group`, date), 0) AS samecolor FROM `table`),sequences AS (SELECt `group`, date, color, SUM(samecolor = 0) OVER (ORDER BY `group`, date) AS seq_num FROM cte)SELECt `group`, date, color, ROW_NUMBER() OVER (PARTITION BY seq_num) AS `rank`FROM sequencesORDER BY `group`, date
输出:
group date color rankA 1-1-2019 R 1A 1-2-2019 Y 1B 1-1-2019 R 1B 1-2-2019 Y 1B 1-3-2019 Y 2B 1-4-2019 R 1B 1-5-2019 R 2B 1-6-2019 R 3
dbfiddle上的演示
请注意
Y,如果您希望将值
NULL替换
rank为此的定义,则此查询还会给出值的排名:
CASE WHEN color = 'Y' THEN NULL ELSE ROW_NUMBER() OVER (PARTITION BY seq_num) END AS `rank`
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)