0

我有一个历史表,其中包含每个客户的记录,其中 start_date 和 end_date 列指示每行的有效期。该表如下所示:

| ID  | Name | Code  |start_date (Timestamp) |end_date (Timestamp) |
|:--- |:----:|:-----:|----------------------:|--------------------:|
|123  | John | 100   |2021/1/6   8:00:00     |2021/1/31  8:00:00   | 
|123  | John | 101   |2021/1/31  8:00:00     |2021/2/15  8:00:00   | 
|123  | John | 102   |2021/2/15  8:00:00     |2021/3/15  8:00:00   | 
|123  | John | 103   |2021/3/15  8:00:00     |2021/6/15  9:00:00   | 
|123  | John | 105   |2021/6/15  9:00:00     |2021/6/15  9:15:00   | 
|123  | John | 106   |2021/6/15  9:15:00     |2021/6/15 10:00:00   |
|123  | John | 107   |2021/6/15 10:00:00     |2021/7/15 15:00:00   | 
|123  | John | 108   |2021/7/15 15:00:00     |null                 |

我决定使用“展开”功能来生成一个显示“每月”记录(每个月末记录)的列。所需的输出应该是这样的,如果 end_date 为空,它应该将记录展开到当前日期,但我的展开语法不能正常工作:

| ID  | Name | Code  |start_date (Timestamp) |end_date (Timestamp) |end_of_month
|---- |------|-------|-----------------------|---------------------|------------
|123  | John | 101   |2021/1/31  8:00        |2021/2/15  8:00:00   | 2021/1/31
|123  | John | 102   |2021/2/15  8:00        |2021/3/15  8:00:00   | 2021/2/28
|123  | John | 103   |2021/3/15  8:00        |2021/6/15  9:00:00   | 2021/3/31
|123  | John | 103   |2021/3/15  8:00        |2021/6/15  9:00:00   | 2021/4/30
|123  | John | 103   |2021/3/15  8:00        |2021/6/15  9:00:00   | 2021/5/31
|123  | John | 107   |2021/6/15 10:00        |2021/7/15 15:00:00   | 2021/6/30
|123  | John | 108   |2021/7/15 15:00        |?                    | 2021/7/30
|123  | John | 108   |2021/7/15 15:00        |?                    | 2021/8/31
|123  | John | 108   |2021/7/15 15:00        |?                    | 2021/9/30

我有以下 sql,但它不包括最后一条记录,即 end_of 月“2021/9/30”。如果我将 ANCHOR 设置为“MONTH_BEGIN”,则会出现记录“2021/9/30”,但它会排除记录 2021/7/30 作为回报。

select a.id, a.name, a.code, a.start_date, a.end_date, last_day(BEGIN(bg2)) 
as end_of_month from (select id, name, code, start_date, end_date, 
period(start_date,COALESCE(MIN(start_date) OVER (PARTITION BY name ORDER BY start_date 
ROWS BETWEEN 1 FOLLOWING AND 1 FOLLOWING), CURRENT_TIMESTAMP)) as bg from CHESS.HST) as a
expand on bg as bg2 by ANCHOR MONTH_END
4

1 回答 1

2

这似乎符合您要求的结果:

select a.id, a.name, a.code, a.start_date, a.end_date,
   last_day(begin(bg2)) as end_of_month
from
 (
   select id, name, code, start_date, end_date, 
      period(start_date,COALESCE(end_date
                                ,add_months(CURRENT_TIMESTAMP(0), 1)
                                )
            ) as bg
   from HST
 ) as a
expand on bg as bg2 
    by ANCHOR MONTH_END
于 2021-09-27T18:03:48.230 回答