如何在 SQL 中创建一列来显示特定月份是否在两个日期之间

问题描述 投票:0回答:1

我想为每个月创建列,如果该月位于两个日期之间,则将该月设置为 true。

例如,我的日期为= 2023-01-01,日期为= 2023-05-31

所以我希望 2023-02 列的值 = 1,因为本月位于这些日期之间

但是第 2023-06 列将得到值 = 0,因为本月超出范围。

现在我有桌子了

Customer nr Date from   Date to
   xxxxxx    2023-01-01 2023-05-31
   yyyyyy    2023-03-01 2023-10-31
   qqqqq     2023-08-01 2023-12-31

但我想要:

Customer nr Date from   Date to 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
   qqqqq    2023-08-01  2023-12-31  0      0      0
sql sql-server case between
1个回答
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;

否则,当使用范围重叠检查(包括开始和结束)时:

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;

数据库<>小提琴

© www.soinside.com 2019 - 2024. All rights reserved.