我想在每个月的结果中添加一列。如果该列位于两个日期之间(日期来自同一行),则该列应包含 true。
例如,我的日期为= 2023-01-01,日期为= 2023-05-31
所以我希望 2023-02 列的值 = 1,因为本月位于这些日期之间
但是第 2023-06 列将得到值 = 0,因为本月超出范围。
现在我有桌子了
客户编号 | 日期从 | 日期 |
---|---|---|
xxxxxx | 2023-01-01 | 2023-05-31 |
yyyyyy | 2023-03-01 | 2023-10-31 |
qqqqq | 2023-08-01 | 2023-12-31 |
但我想要:
客户编号 | 日期从 | 日期 | 2023.01 | 2023.02 | 2023.03 |
---|---|---|---|---|---|
xxxxxx | 2023-01-01 | 2023-05-31 | 1 | 1 | 1 |
yyyyyy | 2023-03-01 | 2023-10-31 | 0 | 0 | 1 |
qqqq | 2023-08-01 | 2023-12-31 | 0 | 0 | 0 |
如果
date_from
始终是该月的第一天,而 date_to
始终是该月的最后一天,则使用简单的 between
检查:
select *
, case when '2023-01-01' between date_from and date_to then 1 else 0 end as [2023-01]
, case when '2023-02-01' between date_from and date_to then 1 else 0 end as [2023-02]
, case when '2023-03-01' between date_from and date_to then 1 else 0 end as [2023-03]
from t;
否则使用范围重叠检查(月份的某些部分与 [date_from, date_to] 范围的某些部分相交):
select *
, case when date_to >= '2023-01-01' AND date_from <= eomonth('2023-01-01') then 1 else 0 end as [2023-01]
, case when date_to >= '2023-02-01' AND date_from <= eomonth('2023-02-01') then 1 else 0 end as [2023-02]
, case when date_to >= '2023-03-01' AND date_from <= eomonth('2023-03-01') then 1 else 0 end as [2023-03]
from t;