I have a table cars
, which has fields make
model
and update_at
.
updated_at
is a DateTime
make | model | updated_at
----------------------------------
Ford | Fiesta | 12-Jan-2010
Chevy | Sliverado | 13-Jan-2010
Ford | Focus 开发者_StackOverflow中文版 | 13-Jan-2010
I want to find the last updated car of each make like:
make | model | updated_at
---------------------------------
Chevy | Sliverado | 13-Jan-2010
Ford | Focus | 13-Jan-2010
Normally I would just group by
but in postgresql if I group by make
I have to include any other selected columns in the group by
or in an aggregate function.
How do I get my desired result.
PostgreSQL 8.4+:
WITH sample AS (
SELECT t.make,
t.model,
t.updated_at,
ROW_NUMBER() OVER(PARTITION BY t.make
ORDER BY t.updated_at DESC) AS rank
FROM CARS t)
SELECT s.make,
s.model,
s.updated_at
FROM sample s
WHERE s.rank = 1
PostgreSQL prior to 8.4:
This uses a self join, but the problem is you'll get duplicates if a make has two or more models with the same maximum updated_at value:
SELECT x.make,
x.model,
x.updated_at
FROM CARS x
JOIN (SELECT t.make,
MAX(t.updated_at) AS max_date
FROM CARS t
GROUP BY t.make) y ON y.make = x.make
AND y.max_date = x.updated_at
精彩评论