【发布时间】:2022-06-23 01:51:14
【问题描述】:
输入
month seller product amount
2021-10-01 A corn 20€
2021-10-02 A corn 40€
2021-10-02 B grain 30€
2021-10-03 B grain 10€
2021-10-03 A corn null
.....
我想统计每个月与上个月农产品采购的增量(差异),并用以下事件标记它们:
(if cost purchase this month > cost purchase last month --> increase
if cost purchase this month < cost purchase last month --> decrease
if cost purchase this month = x and cost purchase last month is null or 0 --> new
if cost purchase this month is null or 0 and cost purchase last month is not null --> stop
)
预期输出:
month seller product amount last_month_amount delta event
2021-10-01 A corn 20€ null 20€ new
2021-10-02 A corn 40€ 20€ 20€ increase
2021-10-02 B grain 30€ null 30€ new
2021-10-03 B grain 10€ 30€ -20€ decrease
2021-10-03 A corn null 40€ -40€ stop
如果只有一种产品, 我能做到:
select month
, seller
, product
, amount
, lag(amount) over (partition by seller,product order by month) as last_month_amount
, amount - last_month_amount as delta
, case when delta >0 and min(month) over (partition by seller) = month then 'new'
when delta >0 then 'increase'
when delta <0 then 'decrease'
when (delta is null or delta = 0) then 'stop'
end as event
但是,在同一个月份生产多种农产品是不合逻辑的。 我怎样才能将一个产品的逻辑调整为多个产品?
我想如果我尝试获取玉米的 last_month_amount,它会返回上个月的谷物数量。我可以使用“case when”,但如果产品很多,它就不起作用了。
【问题讨论】:
标签: postgresql