[英]Set value for group by order
I have SQL table with columns COL_1, COL_2:我有 SQL 表,其中包含 COL_1、COL_2 列:
COL_1 ![]() |
COL_2 ![]() |
COL_3 ![]() |
---|---|---|
a![]() |
2021-09-11 14:25:15.699 ![]() |
1 ![]() |
b ![]() |
2021-09-11 14:25:36.489 ![]() |
2 ![]() |
a![]() |
2021-09-11 14:33:36.500 ![]() |
3 ![]() |
a![]() |
2021-09-11 14:36:24.915 ![]() |
3 ![]() |
a![]() |
2021-09-11 14:36:38.900 ![]() |
3 ![]() |
a![]() |
2021-09-11 14:36:54.905 ![]() |
3 ![]() |
c ![]() |
2021-09-11 14:37:09.092 ![]() |
4 ![]() |
a![]() |
2021-09-11 14:39:09.111 ![]() |
5 ![]() |
d ![]() |
2021-09-11 14:39:30.292 ![]() |
6 ![]() |
I need to get COL_3.我需要得到 COL_3。 I got column 4 by grouping column 1 and sorting by date (column 2), if the group changes, I assign a new index for the following groups.
我通过对第 1 列进行分组并按日期(第 2 列)排序得到第 4 列,如果组发生变化,我会为以下组分配一个新索引。
This is a classic gaps-and-islands problem.这是一个经典的缺口和孤岛问题。
There are many solutions.有很多解决方案。 A common one is to use
LAG
to identify rows which change value, then a conditional windowed COUNT
to assign the group numbers一个常见的方法是使用
LAG
来识别更改值的行,然后使用条件窗口化的COUNT
来分配组号
WITH PrevValues AS (
SELECT *,
LAG(COL_1) OVER (ORDER BY COL_2) AS PrevCol1
FROM YourTable t
)
SELECT COL_1,COL_2,COL_3,
COUNT(CASE WHEN PrevCol1 = COL_1 THEN NULL ELSE 1 END)
OVER (ORDER BY COL_2 ROWS UNBOUNDED PRECEDING) AS New_Col_3
FROM PrevValues t
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.