帮助t-sql自我加入

时间:2010-06-11 21:55:17

标签: sql-server tsql sql-server-2008 self-join

基于下表

ID  Date         State 
-----------------------------
1   06/10/2010   Complete
1   06/04/2010   Pending
2   06/06/2010   Active   
2   06/05/2010   Pending

我想要以下ouptut

ID  Date         State 
---------------------------
1   06/04/2010   Complete
2   06/05/2010   Active

所以约会是最早的,国家是最新的。我无法在表上应用自联接来获取输出。

由于

2 个答案:

答案 0 :(得分:1)

使用:

  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

答案 1 :(得分:0)

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