在sql server中获取唯一值

时间:2011-11-08 18:11:17

标签: sql-server-2008

我有一张桌子说:

id| AccID | Subject      | Date                       
1 | 103   | Open HOuse 1 | 11/24/2011 9:00:00 AM        
2 | 103   | Open HOuse 2 | 11/25/2011 10:00:00 AM       
3 |  72   | Open House 3 | 11/26/2011 1:10:28 AM        
4 |  82   | OPen House 4 | 11/27/2011 5:00:29 PM        
5 |  82   | OPen House 5 | 11/22/2011 5:00:29 PM   

从上表中,我需要Accid的所有唯一值。但是,如果有两个或更多列具有相同的Accid,那么我需要一个具有较小日期的列(在具有相同Accid的列中)

所以,从上表中,o / p应该是: 1 3 5

任何人都可以帮助我吗?感谢

2 个答案:

答案 0 :(得分:1)

不仅仅是AccID,还有......

WITH SEL
AS
(
    SELECT AccID, MIN(DATE)
      FROM table
     GROUP BY AccID
)
SELECT table.*
  FROM table
  JOIN SEL ON SEL.AccID = table.AccID

答案 1 :(得分:1)

SELECT t1.*
FROM [MyTable] t1
INNER JOIN
(
    SELECT AccID, MIN(Date) Date
    FROM [MyTable]
    GROUP BY AccID
) t2 ON t1.AccID = t2.AccID AND t1.Date = t2.Date