sql - 如何在 Redshift 中自行加入日期计算和其他字段
问题描述
得到一个查询,该查询获取按日期、运营商、来源、路线分组的预订数据,我想自行加入它,以便我拥有相同的数据,但在前一年的日期加入(添加 1 天以对齐工作日)。
例如,如果我们有
date |num|
----------|---|
2017-01-01|300|
2017-01-02|301|
2017-01-03|302|
2017-01-04|303|
2017-01-05|304|
2017-01-06|305|
2017-01-07|306|
2017-01-08|307|
2017-01-09|308|
2017-01-10|309|
...
2018-01-01|501|
2018-01-02|502|
2018-01-03|503|
2018-01-04|504|
2018-01-05|505|
2018-01-06|506|
2018-01-07|507|
2018-01-08|508|
2018-01-09|509|
2018-01-10|510|
...
然后我希望结果是
date |num| date |num|
----------|---| ----------|---|
2017-01-01|300| null |null|
2017-01-02|301| null |null|
2017-01-03|302| null |null|
2017-01-04|303| null |null|
2017-01-05|304| null |null|
2017-01-06|305| null |null|
2017-01-07|306| null |null|
2017-01-08|307| null |null|
2017-01-09|308| null |null|
2017-01-10|309| null |null|
...
2018-01-01|501| 2017-01-02|301|
2018-01-02|502| 2017-01-03|302|
2018-01-03|503| 2017-01-04|303|
2018-01-04|504| 2017-01-05|304|
2018-01-05|505| 2017-01-06|305|
2018-01-06|506| 2017-01-07|306|
2018-01-07|507| 2017-01-08|307|
2018-01-08|508| 2017-01-09|308|
2018-01-09|509| 2017-01-10|309|
2018-01-10|510| 2017-01-11|...|
到目前为止我所拥有的
select
a.date as date1
,a.source as source1
,a.operator as operator1
,a.route as route1
,a.sum as bookings1
,b.date as date2
,b.source as source2
,b.operator as operator2
,b.route as route2
,b.sum as bookings2
from
(select
date
,source
,operator
,route
,sum(record_count)
from booking
where transaction_date >= dateadd(year, -2, current_date)
group by 1,2,3,4) a
full outer join
(select
date
,source
,operator
,route
,sum(record_count)
from booking
where date between dateadd(year, -3, current_date) and dateadd(year, -1, current_date)
group by 1,2,3,4) b
on
b.date = dateadd(day, 1, dateadd(year, -1, a.date))
and a.source = b.source
and a.outbound_operator_name = b.outbound_operator_name
and a.outbound_route_name = b.outbound_route_name
;
上述查询的问题在于它显示的是正确的 2018 年结果,但不是正确的 2017 年结果。我认为连接类型或 on 子句中的某些内容有问题,例如日期计算尝试...
任何帮助将非常感激
解决方案
推荐阅读
- android-source - AOSP Build ID 在哪里/如何设置?
- google-sheets - 谷歌表格导入错误?多行缺失数据
- python - 如何导入文件名与数据框中的列值对应的图像?
- amazon-web-services - AWS HTTP API Gateway 503 服务不可用
- regex - 正则表达式:多行,非贪婪匹配,直到可选字符串
- c# - Azure App Service Linux Web App:找不到任何已安装的 .NET Core SDK
- pandasgui - pandasgui ImportError:无法从“打字”中导入名称“文字”(C:\ Users \ sefater \ anaconda3 \ lib \ typing.py)
- c# - unity IAP 购买的非消耗性场景如何保存?
- javascript - 我可以从包含带有 JavaScript 的动态部分的简单站点生成用于电子邮件模板的静态 HTML/CSS
- r - 仅排除 NA 值而不是 R 中 lm 中的整行?