简体   繁体   中英

Group by latest value sql

Forecast date            date          Value  Object     Demand or supply
01-01-2016 00:30    12-10-2019 00:00    85    Ice-cream     Demand
04-07-2018 02:59    26-12-2019 00:00    83    Crisps        Supply
07-08-2018 03:25    29-02-2020 00:00    50    Juice         Demand
29-10-2018 03:25    09-05-2020 00:00    76    Juice         Supply
25-02-2019 03:25    07-08-2020 00:00    74    Juice         Demand
01-07-2019 03:25    11-10-2020 00:00    69    Crisps        Demand
17-10-2019 03:25    17-12-2020 00:00    77    Meal          Supply
06-01-2020 03:25    29-03-2021 00:00    87    Eggs          Demand

I have a dataframe like the above where the forecast keeps coming in for a particular date as more data becomes available

I want to get the latest forecasted value foe a certain date for each object and group demand and supply separately.

Logic-
-Latest forecast date for each date value and object
- Group demand/supply and object with Date desc

Desired output

Forecast Date   Date    Demand or supply    Object  Value
01-01-2020  01-11-2021  Demand            Ice-Cream 60
01-01-2020  01-10-2021  Demand            Ice-Cream 80
01-01-2020  01-09-2021  Demand             Crisps   70
01-01-2020  01-08-2020  Supply             Crisps   70
01-11-2019  01-07-2020  Supply             Crisps   85
01-11-2019  01-06-2020  Supply             Crisps   80

So to provide clarity for an entry in the date column -I would like the value to be the one in the latest forecast date. -Then group the table by demand/supply then group by object and finally group by date,therefore getting a corresponding time-series of values for each object on the demand/supply side

If I understand correctly, you can use row_number() :

select t.*
from (select t.*,
             row_number() over (partition by object, demand_group, date order by forecast_date desc) as seqnum
      from t
     ) t
where seqnum = 1;

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