分组依据和“第一”或“分钟”

时间:2012-09-27 13:47:34

标签: postgresql aggregate

我有一个表“messages”,其中包含列id,from,to,datetime,subject,body。我希望为每个发件人(来自)获取最新消息的主题和正文。

这是我的查询

SELECT min(subject) as tsubject,min(body) as tbody 
FROM messages 
WHERE "to"=28
GROUP BY "from"
ORDER BY "datetime"

这将导致

ERROR:  column "messages.datetime" must appear in the GROUP BY clause or be used in an aggregate function

所以我得到了错误的全部内容,但我不想按“datetime”对结果进行分组,只是要对要排序的组进行分组,以便min选择每个组的最新消息。

2 个答案:

答案 0 :(得分:1)

select subject, body, m."from"
from (
    SELECT 
        id,
        "from",
        max("datetime")
    FROM messages 
    WHERE "to" = 28
    group by id, "from"
    ) s 
    inner join 
    messages m on m.id = s.id
ORDER BY "datetime" desc

答案 1 :(得分:1)

SELECT a.*,u.name,m.subject,m.body FROM
(SELECT "from",max("datetime") as sent
FROM messages 
WHERE "to" = 31
GROUP BY "from") a
LEFT JOIN users u ON a."from" = u.id
LEFT JOIN messages m ON a.sent=m."datetime" AND a."from"=m."from"