简体   繁体   中英

How to find latest effective price for each month DB2 SQL

I`m trying to build a query that will the latest established price for each month within a year for two price types. A price may or may not change each month for each item and type. Below is my source table

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

And this is what I`m trying to achieve

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

Thank you!

DB2 doesn't have (to the best of my knowledge) aggregation functions for getting the first element. One relatively simple way is to use the first_value() window function:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM