刚才的帖子SQL实例给错了,再开一贴
create table testA(id int,fdate datetime)
create table testB(id int,fid varchar(10),fremark varchar(10))
insert into testA values(1,'2013-08-01');
insert into testA values(2,'2013-08-03');
insert into testA values(3,'2013-08-07');
insert into testA values(4,'2013-08-06');
insert into testB values(1,'A1','')
insert into testB values(1,'B1','')
insert into testB values(2,'A1','')
insert into testB values(2,'B1','')
insert into testB values(3,'B1','')
insert into testB values(4,'A1','')
insert into testB values(4,'B1','')
3,'2013-08-07','B1'
4,'2013-08-06','A1'
;WITH cte AS
(
SELECT b.*,a.fdate
FROM testA a
INNER JOIN testB b
ON a.id = b.id
)
SELECT b.id,fdate=CONVERT(CHAR(10), b.fdate,120),b.fid FROM
(SELECT DISTINCT fid FROM testB) a
CROSS APPLY
(SELECT TOP(1) * FROM cte m WHERE m.fid=a.fid ORDER BY m.fdate DESC) b
/*
idfdatefid
42013-08-06A1
32013-08-07B1
*/
;WITH cte AS
(
SELECT b.*,a.fdate
FROM testA a
INNER JOIN testB b
ON a.id = b.id
)
SELECT * FROM cte a
WHERE NOT EXISTS
(
SELECT 1
FROM cte b
WHERE b.fid = a.fid
AND b.fdate > a.fdate
)
/*
idfidfremarkfdate
4A12013-08-06 00:00:00.000
3B12013-08-07 00:00:00.000
*/