There is a table with the url and created_at fields.
There are many entries in the table with the same url . I need to get entries with the most senior created_at , for each group with the same url . Ie, having:
url | created_at ------------------------ abc | 1 abc | 2 def | 3 def | 0 Receive:
url | created_at ------------------------ abc | 2 def | 3 Tried to do it like this:
SELECT * FROM items GROUP BY url HAVING created_at = MAX(created_at) I receive:
ERROR: column "items.id" must appear in the GROUP BY clause or be used in an aggregate function I tried the same thing a little differently:
SELECT MAX(created_at) AS last_created_At, * FROM items GROUP BY url HAVING created_at = last_created_at Received:
ERROR: column "last_created_at" does not exist LINE 4: HAVING created_at = last_created_at` Looks like I misunderstand how GROUP BY HAVING works. How do I get what I want?
ADDED: Reached the desired with the help of a subquery, but the question remains open, how to do it without him:
SELECT * FROM items WHERE created_at = (SELECT MAX(created_at) FROM items AS t WHERE t.url = items.url)
SELECT *. If you add*to your request, it will return entries that I don’t need, just by adding a maximum, without filtering. - Vladimir Gordeev