我正在尝试建立一个查询,以查询两种价格类型在一年内每个月的最新确定价格。每个项目和类型每个月的价格可能会或可能不会改变。下面是我的源表
item | date | type | price
------------------------------
itm1 | 20180101 | 1 | 3
itm1 | 20180101 | 2 | 1
itm1 | 20180105 | 1 | 5
itm2 | 20180101 | 1 | 8
itm2 | 20180103 | 2 | 6
itm2 | 20180105 | 2 | 5
itm3 | 20171215 | 1 | 7
itm3 | 20180201 | 1 | 9
itm3 | 20180201 | 2 | 10
这就是我想要实现的目标
item | YYYMM |type1_prc | type1_last(max) |type2_prc | typ2_last(max)
| | | effective_date | | effective_date
---------------------------------------------------------------------------
itm1 | 201801 | 5 | 20180105 | 1 | 20180101
itm2 | 201801 | 8 | 20180101 | 5 | 20180105
itm3 | 201801 | 7 | 20171215 | - | -
itm1 | 201802 | 5 | 20180105 | 1 | 20180101
itm2 | 201802 | 8 | 20180101 | 5 | 20180105
itm3 | 201802 | 9 | 20180201 | 10 | 20180201
谢谢!
答案 0 :(得分:0)
据我所知,DB2没有用于获取第一个元素的聚合函数。一种相对简单的方法是使用first_value()
窗口函数:
select distinct item, to_char(date, 'YYYY-MM') as yyyymm,
first_value(price) over (partition by item, to_char(date, 'YYYY-MM') order by type asc) as type1_price,
max(case when type = 1 then price end) as type1_date
first_value(price) over (partition by item, to_char(date, 'YYYY-MM') order by type desc) as type2_price,
max(case when type = 2 then price end) as type2_date
from t