문제

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

도움이 되었습니까?

해결책

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top