日期:2014-05-17  浏览次数:20367 次

刚才的帖子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','')


result

3,'2013-08-07','B1'
4,'2013-08-06','A1'

------解决方案--------------------
select a.*,b.fid into testc from testa a inner join testb b on a.id=b.id
select * from testc c where (select count(*) from testc where fid=c.fid and fdate>c.fdate)=0
------解决方案--------------------
;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