我有这个SQL查询:
SELECT
users.id,
users.name,
users.avatar,
MAX(messages.created_at) max_created_at,
MAX(messages.body) FILTER (WHERE messages.created_at = MAX(messages.created_at)) last_message,
CASE WHEN(COUNT(messages.is_read) FILTER (WHERE is_read = false AND messages.from_id != 14) = 0) THEN true ELSE false END is_read,
COUNT(messages.is_read) FILTER (WHERE is_read = false AND messages.from_id != 14) count_unread
FROM
messages
INNER JOIN
users ON messages.from_id = users.id OR messages.to_id = users.id
WHERE
(messages.from_id = 14 OR messages.to_id = 14)
AND users.id != 14
GROUP BY
users.id;
但是,此查询显示错误
FILTER中不允许使用聚合函数
当我改变
MAX(messages.body) FILTER (WHERE messages.created_at = MAX(messages.created_at)) last_message
至
MAX(messages.body) FILTER (HAVING messages.created_at = MAX(messages.created_at)) last_message
查询现在显示此错误
“HAVING”或其附近有语法错误
如何解决这个问题?
2条答案
按热度按时间syqv5f0l1#
可以在
SELECT
的单个示例中使用窗口函数和DISTINCT ON
来完成:相关:
4dc9hkyq2#
我想你需要这样: