如何在Redshift SQL中复用代码实现多时间周期指标聚合至单表
Redshift SQL 复用代码实现多时间周期指标聚合
你可以用条件聚合的方式复用代码,只写一次基础查询(包括JOIN逻辑),通过CASE WHEN在聚合函数里筛选不同时间范围的数据,就能把所有周期的指标整合到一张表中,避免重复编写相同的关联和查询结构。
优化后的代码示例
select c1 as c1, -- 近30天指标 sum(case when date between current_date - 30 and current_date then c2 end) as t30_c2, sum(case when date between current_date - 30 and current_date then c3 end) as t30_c3, max(case when date between current_date - 30 and current_date then c4 end) as t30_c4, -- 近90天指标 sum(case when date between current_date - 90 and current_date then c2 end) as t90_c2, sum(case when date between current_date - 90 and current_date then c3 end) as t90_c3, max(case when date between current_date - 90 and current_date then c4 end) as t90_c4, -- 近120天指标 sum(case when date between current_date - 120 and current_date then c2 end) as t120_c2, sum(case when date between current_date - 120 and current_date then c3 end) as t120_c3, max(case when date between current_date - 120 and current_date then c4 end) as t120_c4 from t1 join t2 on -- 补充实际的表关联条件 join t3 on -- 补充实际的表关联条件 join date_tbl on -- 补充实际的表关联条件 group by c1;
关键说明
- 核心逻辑:用
CASE WHEN判断数据是否落在目标时间范围,符合条件的字段值参与聚合,不符合的返回NULL——聚合函数(sum/max等)会自动忽略NULL,最终结果和单独查询每个时间范围的逻辑完全一致。 - 优势:只需要维护一套基础查询结构,后续新增时间周期时,仅需添加对应的
CASE WHEN聚合列即可,大幅减少重复代码、降低维护成本;同时由于只扫描一次表数据,性能比多次单独查询更优。 - 注意事项:原代码中
join t2 ()这类写法需要补充实际关联条件;必须显式添加group by c1,和原查询的分组逻辑保持一致,避免Redshift语法报错。
内容的提问来源于stack exchange,提问作者ThirdEye
相关产品推荐
相关产品推荐

