Based on the following table
ID Date State
-----------------------------
1 06/10/2010 Complete
1 06/04/2010 Pending
2 06/06/2010 Active
2 06/05/2010 Pending
I want the follow开发者_运维百科ing ouptut
ID Date State
---------------------------
1 06/04/2010 Complete
2 06/05/2010 Active
So date is the earliest one and State is the latest one. I am failing to apply self join on the table to get the output.
Thanks
Use:
SELECT t.id,
MIN(t.date),
(SELECT TOP 1
x.state
FROM TABLE x
WHERE x.id = t.id
ORDER BY x.date DESC)
FROM TABLE t
GROUP BY t.id
select ID, min(Date) Date, (select State
from tbl
where ID = t.ID and
Date = (select max(Date)
from tbl
where ID = t.ID)) State
from tbl t
group by ID
精彩评论