日期:2014-05-17 浏览次数:20725 次
--sql:
SELECT b.* from
(SELECT DISTINCT userid FROM #temp) a
CROSS APPLY
(SELECT TOP(1) * FROM #temp m WHERE m.userid = a.userid ORDER BY InsertDate) b
CREATE TABLE tblTest(ID INT IDENTITY(1,1), UserId INT, InsertDate DATETIME)
INSERT tblTest(userid,InsertDate)
VALUES(1,'2013-10-09 10:11:08.637')
,(1,'2012-10-09 10:11:08.637')
,(2,'2013-10-09 10:11:08.637')
,(2,'2012-10-07 10:11:08.637')
,(2,'2012-10-09 10:11:08.637')
,(3,'2012-10-09 10:11:08.637')
,(3,'2012-10-19 10:11:08.637')
--SELECT * FROM tblTest
SELECT id,userid,InsertDate
FROM (SELECT id,userid,InsertDate,num=ROW_NUMBER() OVER(PARTITION BY userid ORDER BY insertdate) FROM tbltest) a
WHERE num=1
/*结果:
id userid InsertDate
2 1 2012-10-09 10:11:08.637
4 2 2012-10-07 10:11:08.637
6 3 2012-10-09 10:11:08.637
*/