开发者

help with t-sql self join

开发者 https://www.devze.com 2023-01-03 09:08 出处:网络
Based on the following table IDDateState ----------------------------- 106/10/2010Complete 106/04/2010Pending

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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号