SQL-如何选择彼此相邻的最佳两个月

问题描述 投票:0回答:1

如何在postgresql中选择表格中最好的两个月。

Table:

ID Month   Value
1  2019-06  100
2  2019-07  120
3  2019-08  70
4  2019-09  200
5  2019-10  100
6  2019-11  50

我想选择ID,其中彼此相邻的两个月的sum(Value)最高。在以下情况下,结果将是:

4 2019-09
5 2019-10

其中值的总和等于300

sql postgresql algorithm select
1个回答
1
投票

您可以使用join将数据放在一行上:

select t1.*, t2.*
from t t1 join
     t t2
     on t2.month = t1.month + interval '1 month'
order by t1.value + t.value desc
limit 1;
© www.soinside.com 2019 - 2024. All rights reserved.