I have wrecked my brain on this problem for quite some time. I\'ve also reviewed other questions but was unsuccessful.
The problem I have is, I have a list of results/t
This should work in MySQL:
SELECT registration, id, date, unittype FROM
(SELECT registration AS temp_reg, MAX(date) as temp_date
FROM table_name GROUP BY registration) AS temp_table
WHERE registration=temp_reg and date=temp_date
The idea is to use a subquery in a FROM clause which throws up a single row containing the correct date and registration (the fields subjected to a group); then use the correct date and registration in a WHERE clause to fetch the other fields of the same row.
TSQL:
declare @R table
(
Registration varchar(16),
ID int,
Date datetime,
UnitType varchar(16)
)
insert into @R values ('A','1','20090824','A')
insert into @R values ('A','2','20090825','B')
select R.Registration,R.ID,R.UnitType,R.Date from @R R
inner join
(select Registration,Max(Date) as Date from @R group by Registration) M
on R.Registration = M.Registration and R.Date = M.Date
This can be inefficient if you have thousands of rows in your table depending upon how the query is executed (i.e. if it is a rowscan and then a select per row).
In PostgreSQL, and assuming your data is indexed so that a sort isn't needed (or there are so few rows you don't mind a sort):
select distinct on (registration), * from whatever order by registration,"date" desc;
Taking each row in registration and descending date order, you will get the latest date for each registration first. DISTINCT throws away the duplicate registrations that follow.
select registration,ID,date,unittype
from your_table
where (registration, date) IN (select registration,max(date)
from your_table
group by registration)
You want embedded queries, which not all SQLs support. In t-sql you'd have something like
select r.registration, r.recent, t.id, t.unittype
from (
select registration, max([date]) recent
from @tmp
group by
registration
) r
left outer join
@tmp t
on r.recent = t.[date]
and r.registration = t.registration