两个表左连接取数只取一行

 我有两个表
a
id time
1 2011-12-22 10:45:01.000
2 2011-11-22 10:45:01.000
3 2011-12-22 10:45:01.000

b
id time
1 2011-12-22 10:45:01.000
1 2011-11-22 10:45:01.000
2 2011-02-22 10:45:01.000
2 2011-12-22 10:45:01.000
3 2011-11-22 10:45:01.000
3 2011-12-22 10:45:01.000
本来左连接是这么写的
select a.id,a.time,b.id,b.time from
a left join b on a.id=b.id

结果:
id time id time
1 2011-12-22 10:45:01.000 1 2011-12-22 10:45:01.000
1 2011-12-22 10:45:01.000 1 2011-11-22 10:45:01.000
2 2011-11-22 10:45:01.000 2 2011-02-22 10:45:01.000
2 2011-11-22 10:45:01.000 2 2011-12-22 10:45:01.000
3 2011-12-22 10:45:01.000 3 2011-11-22 10:45:01.000
3 2011-12-22 10:45:01.000 3 2011-12-22 10:45:01.000

现在只想取到b表中每个相同id的最后一行数据
结果:
id time id time
1 2011-12-22 10:45:01.000 1 2011-12-22 10:45:01.000
2 2011-11-22 10:45:01.000 2 2011-12-22 10:45:01.000
3 2011-12-22 10:45:01.000 3 2011-12-22 10:45:01.000
求sql怎么写

 

if object_id('[a]') is not null drop table [a]gocreate table [a]([id] int,[time] datetime)insert [a]select 1,'2011-12-22 10:45:01.000' union allselect 2,'2011-11-22 10:45:01.000' union allselect 3,'2011-12-22 10:45:01.000'if object_id('[b]') is not null drop table [b]gocreate table [b]([id] int,[time] datetime)insert [b]select 1,'2011-12-22 10:45:01.000' union allselect 1,'2011-11-22 10:45:01.000' union allselect 2,'2011-02-22 10:45:01.000' union allselect 2,'2011-12-22 10:45:01.000' union allselect 3,'2011-11-22 10:45:01.000' union allselect 3,'2011-12-22 10:45:01.000'

select a.id,a.time,b.id,b.time froma left join b on a.id=b.idand not exists(select 1 from b t where t.id=b.id and t.time>b.time)

/**id time id time----------- ----------------------- ----------- -----------------------1 2011-12-22 10:45:01.000 1 2011-12-22 10:45:01.0002 2011-11-22 10:45:01.000 2 2011-12-22 10:45:01.0003 2011-12-22 10:45:01.000 3 2011-12-22 10:45:01.000(3 行受影响)**/

http://topic.csdn.net/u/20120112/15/74bc9827-ab1b-4cf1-87bf-0763d980b11b.html?seed=32919323&r=77285767#r_77285767

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值