获取最旧的修改价格
Posted
技术标签:
【中文标题】获取最旧的修改价格【英文标题】:Get oldest modified price 【发布时间】:2021-07-08 15:01:14 【问题描述】:我有一个表格,其中每行包含 YYYYMMDD 格式的产品 ID (A)、价格 (P) 和修改日期 (D)。
这是表格:
WITH temp_table AS (
select 744583 as a, 9.21 as p, 20210706 as d from sysibm.sysdummy1
union all
select 744583 as a, 9.21 as p, 20210630 as d from sysibm.sysdummy1
union all
select 744583 as a, 9.21 as p, 20210628 as d from sysibm.sysdummy1
union all
select 744583 as a, 9.04 as p, 20210604 as d from sysibm.sysdummy1
union all
select 744583 as a, 9.04 as p, 20210201 as d from sysibm.sysdummy1
union all
select 744583 as a, 9.21 as p, 20200407 as d from sysibm.sysdummy1
)
select *
from temp_table
what i have
我想要的是价格最后一次变化的时候。在本例中,第三行: enter image description here
你会怎么做?
谢谢,
【问题讨论】:
【参考方案1】:一种方法使用lag()
然后排序:
select t.*
from (select t.*,
lag(p) over (order by d desc) as prev_p
from temp_table t
) t
where prev_p is null or prev_p <> p
order by d desc
fetch first 1 row only;
如果您想同时为多个a
s 执行此操作,则有不同的方法。一个有趣的使用不同的行号:
select a, p, min(date)
from (select t.*,
row_number() over (partition by a order by date desc) as seqnum,
row_number() over (partition by a, p order by date desc) as seqnum_2
from temp_table t
) t
where seqnum = seqnum_2
group by a, p;
您可以调查为什么会这样。这两个行号仅对于每个 a
的最后一个价格是相同的。
【讨论】:
以上是关于获取最旧的修改价格的主要内容,如果未能解决你的问题,请参考以下文章