使用MAX()作为条件

时间:2011-12-01 16:15:49

标签: sql postgresql max

想知道我是否可以在没有子查询的情况下执行此操作

SELECT *
FROM tbl_name
WHERE id = 123456
AND attempts = (
    SELECT MAX(attempts)
    FROM tbl_name
    WHERE id = 123456
)

想要做这样的事情

SELECT *
FROM tbl_name
WHERE id = 123456
AND attempts = MAX(attempts)

我尝试时得到这个:

ERROR:  aggregates not allowed

4 个答案:

答案 0 :(得分:4)

您可以使用窗口函数

来实现
select  *
from    tbl_name
WHERE   id = 123456
        and 1 = row_number() over (partition by id order by attempts desc)

答案 1 :(得分:3)

简短回答是否定的,您不能混合聚合值和非聚合值

答案 2 :(得分:1)

这可能,因为WHERE子句中的条件分别应用于每一行,而MAX是指聚合值,即数据聚合来自一行或多行。

答案 3 :(得分:0)

您可以通过group by语句实现此目的:

SELECT A.ID, MAX(A.Attempts)
FROM Table_Name AS A
WHERE A.ID = 123456
GROUP BY A.ID

或者可能略有不同:

SELECT A.ID, MAX(A.Attempts)
FROM Table_Name AS A
GROUP BY A.ID
HAVING A.ID = 123456