我想用以下公式计算和比较实际季度成本与上一季度成本:(实际年平均成本)/(去年平均每季成本)
我已经完成了实际的季度:
avg ("TOTAL_MONTHLY_COST_IN_USD") OVER (PARTITION BY START_YEARS,
START_QUARTERS ORDER BY "START_QUARTERS" desc) as "PAST_Q"
但最困难的是每季平均获得-1平均成本。在最后的结果中,我希望我的表格看起来像这样:
ACT_Q | PAST_Q | DIVIDE
567.2 | 456.6 | 1.24
为了获得PAST_Q,我尝试使用partition by和PRECEDING。 我有以下支持列进行计算:
START_DATE , START_MONTH, START_QUARTER , START_YEAR .
此外,我使用add_month(x,-12)创建了这些,并将它们称为LAST_YEAR等。
我的第一次尝试: 我在内部选择中分离了sum_cost计算和count_rows,然后将它们分开,但在结果中我只获得了0个值。
case when nvl(quarter_count, 0)<>0 then
sum_totalcost/quarter_count
end as "PAST_AVG_COST_QUARTERLY"
(avg ("TOTAL_MONTHLY_COST_IN_USD") OVER (PARTITION BY START_YEARS, START_QUARTERS ORDER BY ACTUAL_YEAR_QUARTER RANGE BETWEEN 450 PRECEDING AND 0 FOLLOWING) - avg ("TOTAL_MONTHLY_COST_IN_USD") OVER (PARTITION BY START_YEARS, START_QUARTERS ORDER BY ACTUAL_YEAR_QUARTER RANGE BETWEEN 360 PRECEDING AND 0 FOLLOWING)) as sum_cost
(count (*) OVER (PARTITION BY START_YEARS,
START_QUARTERS ORDER BY
ACTUAL_YEAR_QUARTER RANGE BETWEEN 450 PRECEDING AND 0 FOLLOWING) - count (*) OVER
(PARTITION BY START_YEARS, START_QUARTERS
ORDER BY ACTUAL_YEAR_QUARTER RANGE BETWEEN 360 PRECEDING AND 0 FOLLOWING)) as count_rows
任何人都知道如何计算此范围的最佳做法?这真的很有帮助!提前谢谢。
答案 0 :(得分:1)
幸运的是,通过使用“WITH”语句创建了2个表,我解决了这个问题。该表包含实际平均成本/季度。两个表都有这些数据: act_YEAR | act_QUARTER | past_YEAR | past_QUARTER | COUNTRY | MONTHLY_COST 那年我加入了第一张桌子&amp;季度与第二个表行为年和&amp;四分之一。