A表
编号 状态
1 进行
2 进行
3 进行
4 完成
5 完成B表
编号 姓名 时间
1 A 10:00
1 A 9:00
2 X 9:01
2 X 10:12
3 B 12:00
3 B 13:00
3 B 11:45我想获得如下效果:编号 姓名 最后时间
1 A 10:00
2 X 10:12
3 B 13:00
我写了个语句,查是查出来了,可是速度超级慢,大概要3分钟,请问要如何优化语句呢?
B表有12W记录select distinct 姓名
,催收时间 = (select max(时间) from B where A.姓名=B.姓名)
from A
where A.编号=B.任务编号
and 状态='进行'
编号 状态
1 进行
2 进行
3 进行
4 完成
5 完成B表
编号 姓名 时间
1 A 10:00
1 A 9:00
2 X 9:01
2 X 10:12
3 B 12:00
3 B 13:00
3 B 11:45我想获得如下效果:编号 姓名 最后时间
1 A 10:00
2 X 10:12
3 B 13:00
我写了个语句,查是查出来了,可是速度超级慢,大概要3分钟,请问要如何优化语句呢?
B表有12W记录select distinct 姓名
,催收时间 = (select max(时间) from B where A.姓名=B.姓名)
from A
where A.编号=B.任务编号
and 状态='进行'
select 编号,姓名,时间 as 最后时间
from tb a
where not exists(select 1 from tb where a.编号 = 编号 and 时间>a.时间)
select 编号,姓名,时间 as 最后时间 from tb a
where not exists(select 1 from tb where a.编号 = 编号 and 时间>a.时间)
--or
select 编号,姓名,max(时间) as 最后时间 from tb
--or
select 编号,姓名,时间 as 最后时间
from tb a
where (select count(distinct 时间) from tb where a.编号 = 编号 and 时间>=a.时间)=1
from A inner join B
on A.编号=B.编号
where 1>(select count(*) from B where 姓名=a.姓名 and 时间<a.时间)
and 状态='进行'
from A inner join B x
on A.编号=x.编号
where 1>(select count(*) from B where 姓名=x.姓名 and 时间<x.时间)
and 状态='进行'
where not exists(select * from b表 b
where a.编号=b.编号 and a.时间< b.时间)
from A,B
where A.编号=B.任务编号
and A.状态='进行'
group by B.编号,B.姓名
select b.* from b表 a,a表 c
where not exists(select * from b表 b
where a.编号=b.编号 and a.时间< b.时间)
and a.编号=c.编号 and a.状态='进行'
if object_id('tempdb.dbo.#t2') is not null drop table #t2create table #t1 (BH int ,ZT nvarchar(20))create table #t2 (BH int ,XM nvarchar(20),SJ varchar(20))
insert into #t1 values(1, '进行' )
insert into #t1 values(2, '进行' )
insert into #t1 values(3, '进行' )
insert into #t1 values(4, '完成' )
insert into #t1 values(5, '完成' )insert into #t2 values(1, 'A' , '10:00' )
insert into #t2 values(1, 'A' , '9:00' )
insert into #t2 values(2, 'X' , '9:01' )
insert into #t2 values(2, 'X' , '10:12' )
insert into #t2 values(3, 'B' , '12:00' )
insert into #t2 values(3, 'B' , '13:00' )
insert into #t2 values(3, 'B' , '11:45' )select a.BH,XM,SJ as 最后时间
from #t1 a inner join #t2 x
on a.BH=x.BH
where 1>(select count(*) from #t2 where XM=x.XM and SJ<x.SJ)
and ZT='进行'