首页 > 解决方案 > 查询历史数据获取月末数据

问题描述

我们有一个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

我正在尝试编写此查询,但我知道这是错误的,因为值汇总错误,请有人帮忙确定如何获得正确的值?

标签: amazon-web-servicesamazon-redshift

解决方案


尝试:

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

推荐阅读