如何在postgres中获得记录的最小值或最大值?
例如:
SELECT
max(num), max(letter)
FROM (
VALUES
(1, 'c'),
(3, 'a'),
(3, 'b')
) AS t (num,letter);
会给我(3, 'c')
。
问题是你不能做max(ROW(num, letter))
。
然而,我想要一个查找元组的最大值的函数,它将在python 中
>>> max([
(1, 'c'),
(3, 'a'),
(3, 'b'),
])
(3, 'b')
有没有办法在Postgres中轻松做到这一点?
您可以在这里使用LIMIT
查询,这两列有两个排序级别:
SELECT num, letter
FROM yourTable
ORDER BY num DESC, letter DESC
LIMIT 1;
在可能存在两个或多个记录的情况下;捆绑的";作为第一个,然后使用RANK
:
WITH cte AS (
SELECT *, RANK() OVER (ORDER BY num DESC, letter DESC) rnk
FROM yourTable
)
SELECT num, letter
FROM cte
WHERE rnk = 1;
您可以使用NOT EXISTS(...)
,并比较完整的元组:
WITH stuff (num,letter) AS(
VALUES
(1, 'c'),
(3, 'a'),
(3, 'b')
)
SELECT num,letter
FROM stuff t1
WHERE NOT EXISTS (
SELECT * FROM stuff nx
WHERE (nx.num, nx.letter) > (t1.num, t1.letter)
);
简化:
WITH stuff (num,letter) AS(
VALUES
(1, 'c'),
(3, 'a'),
(3, 'b')
)
SELECT num,letter
FROM stuff t1
WHERE NOT EXISTS (
SELECT * FROM stuff nx
WHERE (nx.*) > (t1.*)
);
简化:
WITH stuff (num,letter) AS(
VALUES
(1, 'c'),
(3, 'a'),
(3, 'b')
)
SELECT num,letter
FROM stuff t1
WHERE NOT EXISTS (
SELECT * FROM stuff nx
WHERE (nx) > (t1)
);