求一sql
表A
id jsbh sj1 sj2
1 s-001 2013-1-1 2013-1-3
2 s-002 2013-1-2 2013-1-2
3 s-003 2013-2-2 2013-2-3
表B
id hhbh bh
1 s-001、s-002 b-001
2 s-002 b-002
3 s-002、s-003 b-003
想要的结果
id bh hhbh sj1 sj2
1 b-001 s-001、s-002 2013-1-2 2013-1-3
2 b-002 s-002 2013-1-2 2013-1-2
3 b-003 s-002、s-003 2013-2-2 2013-2-3
前3列是表B中的列,后面2个时间取hhbh包含jsbh中的最晚时间,
比如b-001包含s-001、s-002,在结果中sj1和sj2取得是sj1和sj2之间最晚的时间
------解决方案--------------------这个应该挺简单的吧,就是2表关联 去取 最大值。。。
select b.id, b.bh, b.hhbh, max(sj1) sj1, max(sj2) sj2
from b, a
where regexp_like(b.hhbh, a.jsbh)
group by b.id, b.bh, b.hhbh
order by b.id;
------解决方案--------------------换个函数写一下:
with tt1 as(
select 1 id,'s-001' jsbh,'2013-1-1' sj1,'2013-1-3' sj2 from dual
select 2,'s-002','2013-1-2','2013-1-2' from dual union
select 3,'s-003','2013-2-2','2013-2-3' from dual
),
tt2 as(
select 1 id,'s-001、s-002' hhbh,'b-001' bh from dual union
select 2,'s-002','b-002' from dual union
select 3,'s-002、s-003','b-003' from dual
)
select tt2.id,tt2.bh,tt2.hhbh,max(tt1.sj1),max(tt1.sj2)
from tt1,tt2
where instr(tt2.hhbh,tt1.jsbh)>0
group by tt2.id,tt2.bh,tt2.hhbh
order by tt2.id;