汇总排序
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','')
7B12013-08-03 00:00:00.000
3A12013-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
)
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','')
select * from test1 t
where NOT EXISTS
(
SELECT 1
FROM test1 m
WHERE m.fid = t.fid AND
(
(m.fdate > t.fdate) OR
(m.fdate=t.fdate AND m.id > t.id)
)
)
/*
idfidfdatefremark
3A12013-08-03 00:00:00.000
7B12013-08-03 00:00:00.000
*/