Redshift sum window 函数对数字列的前 1 个和后 1 个数值进行计算,即使这些值不存在
Redshift sum window function over previous 1 and next 1 numerical values of a numeric column, even if these values do not exist
我在 Redshift 上有一个 table,如下所示:
维度 1,维度 2,Built_year(数字列),Units_sold
我需要对维度 1、维度 2 的每个组合的 built_year-1、当前 built_year、built_year+1 的度量求和。
问题是,通过使用 SUM() window 函数,我完成了对 built_year 变量的前一行和下一行的度量求和,在许多情况下,前一行和下一行的度量不是 built_year-1、built_year+1,而是 built_year-3、built_year+2 等。因此并非所有 built_year 值都按顺序在变量中找到built_year.
我的代码是:
with sold_per_cluster as
(
select t2.dimension1 AS make,
t3.dimension2 AS model,
t1.built_year AS built_year,
count(distinct t1.id) as units_sold
from table1 t1
left join table2 t2 ON t2.code = t1.code -- #
left join table3 t3 ON t3.id = t1.type_id -- #
where 1
and t1.paid_bool = 1
and t1.paid_datetime >= getdate() - interval '2 year'
group by 1,2,3
order by 1,2,3 asc
)
select make, model,built_year,
sum(units_sold) over (partition by make,model order by built_year
rows between 1 preceding and 1 following) as units_sold
from sold_per_cluster
group by 1,2,3, units_sold
Redshift 是否有办法对 built_year 的 numeric_value +1、-1 求和,即使它不存在?
'No' 是您问题的答案。
您需要将 units_sold 为 0 的维度和年份的所有组合 UNION 到您的数据,然后 SUM() 销售单位以将零添加到当前数据集。 (SUM() 可以在分组依据和聚合函数之后作为 window 函数 运行 在您的顶部 select 中完成。)这样,您的前一年和下一年的 window 要操作的函数。
我在 Redshift 上有一个 table,如下所示:
维度 1,维度 2,Built_year(数字列),Units_sold
我需要对维度 1、维度 2 的每个组合的 built_year-1、当前 built_year、built_year+1 的度量求和。
问题是,通过使用 SUM() window 函数,我完成了对 built_year 变量的前一行和下一行的度量求和,在许多情况下,前一行和下一行的度量不是 built_year-1、built_year+1,而是 built_year-3、built_year+2 等。因此并非所有 built_year 值都按顺序在变量中找到built_year.
我的代码是:
with sold_per_cluster as
(
select t2.dimension1 AS make,
t3.dimension2 AS model,
t1.built_year AS built_year,
count(distinct t1.id) as units_sold
from table1 t1
left join table2 t2 ON t2.code = t1.code -- #
left join table3 t3 ON t3.id = t1.type_id -- #
where 1
and t1.paid_bool = 1
and t1.paid_datetime >= getdate() - interval '2 year'
group by 1,2,3
order by 1,2,3 asc
)
select make, model,built_year,
sum(units_sold) over (partition by make,model order by built_year
rows between 1 preceding and 1 following) as units_sold
from sold_per_cluster
group by 1,2,3, units_sold
Redshift 是否有办法对 built_year 的 numeric_value +1、-1 求和,即使它不存在?
'No' 是您问题的答案。
您需要将 units_sold 为 0 的维度和年份的所有组合 UNION 到您的数据,然后 SUM() 销售单位以将零添加到当前数据集。 (SUM() 可以在分组依据和聚合函数之后作为 window 函数 运行 在您的顶部 select 中完成。)这样,您的前一年和下一年的 window 要操作的函数。