日期:2014-05-17 浏览次数:20609 次
create table test1 (id int,fid varchar(10),fdate datetime, fremark varchar(100))
insert into test1 values(1,'A1','2013-08-01','')
insert into test1 values(2,'A1','2013-08-02','')
insert into test1 values(3,'A1','2013-08-03','')
insert into test1 values(4,'A1','2013-08-02','')
insert into test1 values(5,'B1','2013-08-01','')
insert into test1 values(6,'B1','2013-08-02','')
insert into test1 values(7,'B1','2013-08-03','')
insert into test1 values(8,'B1','2013-08-02','')
7 B1 2013-08-03 00:00:00.000
3 A1 2013-08-03 00:00:00.000
select * from test1 t
where fdate=(select max(fdate) from test where t.fid=fid)
;WITH maco AS
(
SELECT ROW_NUMBER() OVER (PARTITION BY fid ORDER BY fdate DESC,id desc) AS rid,* FROM test1
)
SELECT id,fid,fdate FROM maco WHERE rid=1
/*
id fid fdate
----------- ---------- -----------------------
3 A1 2013-08-03 00:00:00.000
7 B1 2013-08-03 00:00:00.000
*/
SELECT *
FROM test1 AS A
WHERE fdate=(
SELECT TOP 1 MAX(fdate)
FROM test1 AS B
WHERE A.fid=B.fid
GROUP BY B.fid