views:

22

answers:

2

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 following 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

+1  A: 

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
OMG Ponies
thanks omg ponies. But this is not giving the correct State. It is giving Pending for both rows.
stackoverflowuser
You need an DESC on your ORDER BY.
Paul Kearney - pk
@Paul Kearney: Thx, corrected.
OMG Ponies
Thanks Paul! That worked.
stackoverflowuser
A: 
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
Khorkrak
@Khorkrak: this is giving 4 rows as output.
stackoverflowuser
Yeah I just tested it in MySQL - retry it without the State in the group by - works in MySQL now. As for SQL Server, if it gives you a problem try just surrounding the State expression with some aggregate function like Max()
Khorkrak
That worked ! Thanks Khorkrak.
stackoverflowuser
Cool and tada no need from non-standard SQL extensions either such as TOP ;-)
Khorkrak
TOP is ANSI ;) I'll vote for you if you rework the query to not use a subselect
OMG Ponies
Is doing a sort for every row faster than doing a max or equivalent? What's the plan look like in SQL Server since they have a decent explain plan there as opposed to the piece of crap we're stuck with in MySQL...
Khorkrak
TOP is not ANSI it's just the Microsoft way - the 2003 ANSI standard is quite different - here's a page that compares the variations [TOP N / Limit N](http://troels.arvin.dk/db/rdbms/#select-top-n-standard)
Khorkrak