我有一个表格,其中有以下栏目:账户,有效期_日期,有效期_月份,金额。下月.
account validity_date validity_month amount **required_coloum**
------- ------------- --------------- ------- ----------------
123 15oct2019 201910 400 1000
123 20oct2019 201910 500 1000
123 15nov2019 201911 1000 800
123 20nov2019 201911 0 800
123 15dec2019 201912 800
当我尝试这段代码时,我得到了下一行的值,但这不是我所需要的(每个月可以有不止一行)。
max(amount) over (partition by account order by validity_date rows BETWEEN 1 FOLLOWING AND 1 FOLLOWING) as next_max_amount
account validity_date validity_month amount next_max_amount-INVALID
------- ------------- --------------- ------- ----------------------
123 15oct2019 201910 400 500
123 20oct2019 201910 500 1000
123 15nov2019 201911 1000 0
123 20nov2019 201911 0 800
123 15dec2019 201912 800
SELECT dt.*,
-- fill the NULLs with the previous month's max
Last_Value(CASE WHEN rn = 1 THEN current_max END IGNORE NULLS)
Over (PARTITION BY account
ORDER BY validity_date DESC
ROWS BETWEEN Unbounded Preceding AND 1 Preceding)
FROM
(
SELECT t.*,
-- maximum of current month
Max(amount)
Over (PARTITION BY account, validity_month) AS current_max,
-- to identify the 1st row for each month in the next step
Row_Number()
Over (PARTITION BY account, validity_month
ORDER BY validity_date) AS rn
FROM tab AS t
) AS dt
假设validity_month是一个日期类型的列。
select s1.account, s1.validity_date, s1.validity_month, s1.amount,
s2.amount required_column
from your_table s1
left join (select max(amount) amount, validity_month from your_table group by 2) s2
on (
to_char(s1.validity_month.'yyyymm')=to_char(add_month(s2.validity_month,1),'yyyymm')
)