我们有一个history
表,它保留了记录的所有实例,并标记了当前记录以及何时更改 - 这是它的精简版本
CREATE TABLE *schema*.hist_temp
(
record_id VARCHAR
,record_created_date DATE
,current_flag BOOLEAN
,value int
)
INSERT INTO hist_temp VALUES ('Record A','2018-06-01',1,1000);
INSERT INTO hist_temp VALUES ('Record A','2018-04-12',0,900);
INSERT INTO hist_temp VALUES ('Record A','2018-03-13',0,800);
INSERT INTO hist_temp VALUES ('Record A','2018-01-13',0,700);
所以我们拥有的是记录 A,它已经更新了 3 次,最新的记录标记为 1,但我们希望看到历史记录的所有 4 个实例。
然后我们有一个dates
表,其中包含月份结束日期等:
SELECT
calendar_date
,trunc(month_start) as month_start
FROM common.calendar
WHERE
calendar_year = '2018'
and calendar_date < trunc(sysdate)
ORDER BY 1 desc
示例数据:
calendar_date month_start
2018-06-03 2018-06-01
2018-06-02 2018-06-01
2018-06-01 2018-06-01
2018-05-31 2018-05-01
2018-05-30 2018-05-01
2018-05-29 2018-05-01
2018-05-28 2018-05-01
2018-05-27 2018-05-01
2018-05-26 2018-05-01
2018-05-25 2018-05-01
etc
所需结果:
我希望能够显示以下内容 - 显示2018年记录A的月份开始/结束位置
record_id, month_start, value
Record A, '2018-06-01', 1000
Record A, '2018-05-01', 900
Record A, '2018-04-01', 800
Record A, '2018-03-01', 700
Record A, '2018-02-01', 700
我正在尝试编写此查询,我有一些东西,但知道这是错误的,因为值汇总错误,请有人帮助确定如何获得正确的值吗?
尝试:
SELECT
record_id,
date_trunc('month', record_created_date)::date AS month_start,
value
FROM hist_temp
输出:
Record A 2018-06-01 1000
Record A 2018-04-01 900
Record A 2018-01-01 700
Record A 2018-03-01 800