查找给定间隔

时间:2016-07-27 18:27:54

标签: sql postgresql

假设我有一张这样的桌子,其数量是任意数量的东西(如水果或其他东西,但我们不关心类型)

row  |  amount
_______________

1    |  54
2    |  2
3    |  102
4    |  102
5    |  1

我想选择在给定间隔内具有最大值的行。例如,如果我只想从第2-5行中选择将返回的内容

row  |  amount
_______________

3    |  102
4    |  102

因为它们都包含区间内的最大值,即102.或者如果我选择仅查看1-2行,它将返回

row  |  amount
_______________

1    |  54

因为区间1-2中的最大值仅存在于第1行

我尝试使用各种各样的:

amount= (select MAX(amount) FROM arbitraryTable)

但那只会回归

row  |  amount
_______________

3    |  102
4    |  102

因为102是表的绝对最大值。你能找到给定间隔之间的最大值吗?

2 个答案:

答案 0 :(得分:0)

我会使用rank()max()作为窗口函数:

select t.row, t.amount
from (select t.*, max(amount) over () as maxamount
      from t
      where row between 2 and 4
     ) t
where amount = maxamount;

答案 1 :(得分:0)

您可以使用子查询获取最大值并在WHERE子句中使用它:

SELECT
    row,
    amount
FROM
    arbitraryTable
WHERE
    row BETWEEN 2 AND 5 AND
    amount = (
        SELECT
            MAX(amount)
        FROM
            arbitraryTable
        WHERE
            row BETWEEN 2 AND 5
    );

请记住在主查询和子查询中使用相同的条件:row BETWEEN 2 AND 5

相关问题