日期:2014-05-17 浏览次数:20403 次
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
/*
id fdate fid
4 2013-08-06 A1
3 2013-08-07 B1
*/
;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