amazon-web-services - 查询历史数据获取月末数据
问题描述
我们有一个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
推荐阅读
- python - 匹配两个数据帧之间的值并返回一个值
- php - 使用插入值数组执行准备好的语句不起作用
- sql - OPENJSON 不会将所有文档都选择到 SQL 表中
- azure - 查询 SQL 数据库返回错误:用户“免费试用”登录失败
- mysql - SQL 触发器不起作用 #1407 - 错误的 SQLSTATE:“已批准!”
- apache-kafka - Kafka 流 - 多个主题作为同一来源还是每个来源一个主题?
- crystal-reports - 如何在水晶报表中将字体大小设置为富文本框字段
- r - 定义用户函数以从 tibble 中添加/减去
- jmeter - 在 JMeter 中使用事务控制器是一种好方法吗?
- python - 如何在 Python 中使用方括号的类中实现方法(如 pandas DataFrame 中的 loc)?