[英]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我有一个 dataframe 像上面一样,随着更多数据可用,预测会在特定日期不断出现
I want to get the latest forecasted value foe a certain date for each object and group demand and supply separately.我想获得每个 object 和单独分组需求和供应的特定日期的最新预测值。
Logic-
-Latest forecast date for each date value and object
- Group demand/supply and object with Date desc
Desired output所需 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 - 然后按需求/供应对表格进行分组,然后按 object 分组,最后按日期分组,因此在需求/供应侧为每个 object 获得相应的时间序列值
If I understand correctly, you can use row_number()
:如果我理解正确,您可以使用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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.