查询出每个id字段相同的第一条记录
有如下表
ID UserId InsertDate
1 1 2013-10-09 10:11:08.637
2 1 2012-10-09 10:11:08.637
3 2 2013-10-09 10:11:08.637
4 2 2012-10-07 10:11:08.637
5 2 2012-10-09 10:11:08.637
6 3 2012-10-09 10:11:08.637
7 3 2012-10-19 10:11:08.637
需要取每个用户ID相同 并且时间最早的第一条数据
请问查询语句怎么写 数据 查询 语句
[解决办法]
--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
/*结果:
iduseridInsertDate
212012-10-09 10:11:08.637
422012-10-07 10:11:08.637
632012-10-09 10:11:08.637
*/