Sql 基于组内连续两天向表中添加指标列
我需要添加一个逻辑,帮助我将连续两天中的第一天标记为1,第二天标记为0,并按列分组(测试)。如果测试(a)连续三天,则第三天应以1开始,以此类推 示例表如下所示,新列是我需要的列Sql 基于组内连续两天向表中添加指标列,sql,sql-server,window-functions,gaps-and-islands,Sql,Sql Server,Window Functions,Gaps And Islands,我需要添加一个逻辑,帮助我将连续两天中的第一天标记为1,第二天标记为0,并按列分组(测试)。如果测试(a)连续三天,则第三天应以1开始,以此类推 示例表如下所示,新列是我需要的列 |---------------------|------------------|---------------------| | test | test_date | new col | |---------------------|-------
|---------------------|------------------|---------------------|
| test | test_date | new col |
|---------------------|------------------|---------------------|
| a | 1/1/2020 | 1 |
|---------------------|------------------|---------------------|
| a | 1/2/2020 | 0 |
|---------------------|------------------|---------------------|
| a | 1/3/2020 | 1 |
|---------------------|------------------|---------------------|
| b | 1/1/2020 | 1 |
|---------------------|------------------|---------------------|
| b | 1/2/2020 | 0 |
|---------------------|------------------|---------------------|
| b | 1/15/2020 | 1 |
|---------------------|------------------|---------------------|
因为这似乎是一些缺口和孤岛问题,我认为一些windows函数方法应该可以让我达到这一点
我尝试了一些类似于下面的方法来获得连续的部分,但与指示柱的关系很不好
Select
test,
test_date,
grp_var = dateadd(day,
-row_number() over (partition by test order by test_date), test_date)
from
my_table
这确实是一个缺口和孤岛问题。我建议使用
row_number()
和日期之间的差异来生成组,然后使用算术:
select
test,
test_date,
row_number() over(
partition by test, dateadd(day, -rn, test_date)
order by test_date
) % 2 new_col
from (
select
t.*,
row_number() over(partition by test order by test_date) rn
from mytable t
) t
:
test | test_date | new_col
:--- | :--------- | ------:
a | 2020-01-01 | 1
a | 2020-01-02 | 0
a | 2020-01-03 | 1
b | 2020-01-01 | 1
b | 2020-01-02 | 0
b | 2020-01-15 | 1
测试|测试日期|新颜色
:--- | :--------- | ------:
a | 2020-01-01 | 1
a | 2020-01-02 | 0
a | 2020-01-03 | 1
b | 2020-01-01 | 1
b | 2020-01-02 | 0
b | 2020-01-15 | 1