Select 自定义日期范围期间检索上月日的结果

Select a custom date range period to retrieve results from last month day

我有很多数据和很多日期(开始日期、结束日期、激活日期等)。我想检索这些数据 select 特定时间范围和 return 期间日期。

我只想要以下位置的结果:
(上个月日期)<= 激活日期(上个月日期)> 结束日期
+ return 包含 句点

的列

如果我select一个独特的时期:

select "client Name","Program" from "database"."schema"."table" 
WHERE "Date Activation" <= '2020-12-31' AND "Date End" > '2020-12-31' 

目的是检索这样的结果(我想要在我的 table 中的所有时间段):

client Name Program period
client 1 program 1 2020/11/30
client 2 program 2 2020/12/31
client 3 program 3 2020/12/31
client 3 program 3 2021/01/31
client 1 program 1 2021/01/31
client 2 program 4 2021/02/28

我相信这就是您获得前两列的方式:

SELECT DISTINCT "client Name", "Program" 
FROM "database"."schema"."table" 
WHERE "Date Activation" < "Date End" AND LAST_DAY("Date Activation") <> LAST_DAY("Date End")

但是对于第三个,你必须发挥创意。

如果“激活日期”和“结束日期”之间的差异只能是一个月,那么LAST_DAY("Date Activation")就可以了。

但如果差异较大,那么您可能需要两个或更多月末才能上市。您应该在“激活日期”和“结束日期”之间形成某种月末数组。而且你需要从这样的数组中分离出行。

这应该能达到你想要的效果:

-- set parameter to be used as generator "constant" including the start day
-- set start and end dates to match the date range you want to report on
set num_days =  (Select datediff(day, TO_DATE('2020-01-01','YYYY-MM-DD'), current_date()+1));

-- generate all the dates between the start and end dates
with date_list as (
  select
    dateadd(
      day,
      '-' || row_number() over (order by null),
      dateadd(day, '+1', current_date())
    ) as date_val
  from table (generator(rowcount => ($num_days)))
),
-- create a distinct list of month-end dates from the list of dates
month_list as (
  select distinct last_day(date_val) as month_end
  from date_list
)

-- Join the list of month-end dates to your data table
select
cpd.client_name
,cpd.program
,ml.month_end
from month_list ml
inner join client_project_data cpd on cpd.Date_Activation <= ml.month_end and cpd.Date_End > ml.month_end;

-- clean up previously set variable
-- unset num_days;