[英]Previous quarter max month value in big Query
我想使用大查詢查看當前季度中上一季度的最大月份(作為新列)值。
Q4 December 2021
顯示為新列Q1 March 2022
(在本例中為 60000)Q2 June 2022
(在本例中為 40000)我的數據如下
date Sales
2022-09-01 10000
2022-08-02 20000
2022-07-01 30000
2022-06-01 40000
2022-05-01 30000
2022-04-01 50000
2022-03-01 60000
2022-02-01 10000
2022-01-01 89090
Output
您給定的結果表不適合任務:上一季度的最大月份。
這里有幾個輸出。 您想要最近幾個月的最大值,還是三個月前的值? 這兩列都包含在此處。
季度第 1 個月的公式可以通過將 1 更改為 -1 來編輯到上個月。 由於您希望所有其他月份的值為零,因此您需要將其與另一列相乘。
Window function 完成這項工作。 但是每個月必須有一行。 這是用all_months
表填充的。
with tbl as
(
Select date("2022-09-01") as dates, 10000 money
union all select date("2022-08-02"), 20000
union all select date("2022-07-01"), 30000
union all select date("2022-06-01"), 40000
union all select date("2022-05-01"), 30000
union all select date("2022-04-01"), 50000
union all select date("2022-03-01"), 60000
union all select date("2022-02-01"), 10000
union all select date("2022-01-01"), 89090
),
all_months as
(select dates,0 from (Select max(dates) A, min(dates) B from tbl), unnest(generate_date_array(A,B,interval 1 month)) dates)
select *,
if( date_trunc(dates,quarter)= date_trunc(date_sub(dates,interval 1 month),quarter),0,1) as first_month_of_quarter,
lag(money_max_this_quarter) over (order by dates) as money_max_last_quarter,
lag(money,3) over (order by dates) as money_three_months_ago,
from
(
select * ,
max(money) over (partition by date_trunc(dates,quarter ) ) as money_max_this_quarter
from
(
Select dates,sum(money) as money from tbl group by 1
union all select * from all_months
)
)
order by 1 desc
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.