表结构ID. CreatedOn Pid1 2013-09-26 16:24:52.250 11 2013-09-26 16:24:52.327 21 2013-09-26 16:24:52.343 32 2013-09-27 15:09:07.703 42 2013-09-27 15:09:07.720 52 2013-09-27 15:09:07.720 63 2013-09-28 15:09:07.703 73 2013-09-28 15:09:07.720 83 2013-09-28 15:09:07.720 9我想知道 如果按照ID来分组 按照CrteateOn作为条件我想取出最新更改的记录 该怎么SQL语句?注意可能不止3条ID为1或者2或者3的记录。但是CreateOn日期都是一样的
3 回答
largeQ
TA贡献2039条经验 获得超7个赞
select * from TableA where id in (select id from TableA where CreatedON=(select Max(createdOn) as createdon from TableA))
跃然一笑
TA贡献1826条经验 获得超6个赞
USE tempdbGOIF EXISTS(SELECT * FROM SYSOBJECTS WHERE NAME='TEMP') DROP TABLE TEMPCREATE TABLE TEMP( ID INT, CREATED DATETIME, PID INT)GOINSERT INTO TEMPVALUES(1,'2013-01-01 11:11:11',1), (1,'2013-01-01 11:11:12',2), (1,'2013-01-01 11:11:13',3), (2,'2013-01-01 11:11:11',1), (2,'2013-01-01 11:11:12',2), (2,'2013-01-01 11:11:13',3), (2,'2013-01-01 11:11:14',4), (3,'2013-01-01 11:11:11',1), (3,'2013-01-01 11:11:12',2), (3,'2013-01-01 11:11:13',3), (3,'2013-01-01 11:11:14',4)GOSELECT * FROM TEMP AS AWHERE NOT EXISTS(SELECT 0 FROM TEMP AS B WHERE A.ID=B.ID AND A.CREATED<B.CREATED)
白衣染霜花
TA贡献1796条经验 获得超10个赞
select a.*
from table as a
inner join (select id, max(CreatedOn) as CreatedOn
from table
group by id) as b on a.id=b.id and a.CreatedOn=b.CreatedOn
- 3 回答
- 0 关注
- 780 浏览
添加回答
举报
0/150
提交
取消