如何计算行之间的动态平均值?
前12个月status_flag将是N
,从第13个月开始,我们需要获取前13行的平均销售额,并将其与最小值和最大值进行比较,如果它位于最小值和最大值之间然后将status_flag
设置为Y
,将其设置为N
。
相同的第14行取前14行的平均值,并将其与min和max进行比较......依此类推。
怎么做?
答案 0 :(得分:1)
我认为具有挑战性的部分是获得平均销售额。您可以使用Analytic Functions:
select Storeid, Months, Min, Max, sales,
avg(sales) over (order by Months RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as avg_sales
from your_table;
其余的应该更容易。请注意,RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
是默认值,因此您可以跳过它。
with a as
(select Storeid, Months, Min, Max, sales,
avg(sales) over (order by Months) as avg_sales
from your_table)
select Storeid, Months, Min, Max, sales, avg_sales,
case
when Months <= 12 then 'N'
else
case
when avg_sales between Min and Max then 'Y'
else 'N'
end
end as Status_flag
from a;
答案 1 :(得分:0)
Update table t set status_flag =
case when
(Select count(*)
From table
where month <= t.Month) > 12
and
(select avg(sales)
from table
where Month <= t.Month)
Between Min and Max
then 'Y' else 'N' end