日期:2014-05-16  浏览次数:20884 次

求解一个sql语句问题
表A
产编 型号 名称 检验状态
A001 1-1 显示器 ok
A002 1-2 主机箱 ok

表B
产编 检验时间 下次检验时间
A001 2010-01-01 2011-01-01
A001 2011-01-01 2012-01-01
A002 2009-01-01 2009-01-01
A002 2010-01-01 2011-01-01
A002 2011-01-01 2012-01-01


我想查询后结果为:
产编 型号 名称 检验状态 检验时间 下次检验时间
A001 1-1 显示器 ok 2011-01-01 2012-01-01
A002 1-2 主机箱 ok 2011-01-01 2012-01-01


请教大家帮我看看如何写。oracle数据库。





------解决方案--------------------
SQL code

with a as(
select 'A001' 产编,'1-1' 型号,'显示器' 名称,'ok' 检验状态 from dual
union all
select 'A002','1-2','主机箱','ok' from dual
),b as(
select 'A001' 产编,to_date('2010-01-01','yyyy-mm-dd') 检验时间,to_date('2011-01-01','yyyy-mm-dd') 下次检验时间 from dual
union all
select 'A001',to_date('2011-01-01','yyyy-mm-dd'),to_date('2012-01-01','yyyy-mm-dd') from dual
union all
select 'A002',to_date('2009-01-01','yyyy-mm-dd'),to_date('2010-01-01','yyyy-mm-dd') from dual
union all
select 'A002',to_date('2010-01-01','yyyy-mm-dd'),to_date('2011-01-01','yyyy-mm-dd') from dual
union all
select 'A002',to_date('2011-01-01','yyyy-mm-dd'),to_date('2012-01-01','yyyy-mm-dd') from dual
)
select t2.产编,a.型号,a.名称,a.检验状态,t2.检验时间,t2.下次检验时间
  from (select *
          from b t
         where not exists (select 1
                  from b t1
                 where t1.产编 = t.产编
                   and t1.检验时间 > t.检验时间)) t2,
       a
 where t2.产编 = a.产编;
 
产编 型号 名称   检验状态 检验时间    下次检验时间
---- ---- ------ -------- ----------- ------------
A001 1-1  显示器 ok       2011-1-1    2012-1-1
A002 1-2  主机箱 ok       2011-1-1    2012-1-1

------解决方案--------------------
打多了ab
SQL code

select a.产编,a.型号,a.名称,a.检验状态,t1.检验时间,t1.下次检验时间
from a,
     (select b.产编,max(检验时间) 检验时间,max(下次检验时间) 下次检验时间 
      from b
      group by b.产编) t1
where a.产编=t1.产编

------解决方案--------------------
select aa.*,b.*
from (
select a.*,(select b1.rowid 
from test_1204071 b1
where b1.a = a.a
and not exists
(select 1 from test_1204071 
where a=b1.a and c > b1.c)) browid
from test_120407 a) aa, test_1204071 b
where aa.browid = b.rowid;
------解决方案--------------------
SQL code

select a.产编,a.型号,a.名称,a.检验状态,t.检验时间,t.下次检验时间 
from 
    a 
left join
      (select 产编,检验时间,max(下次检验时间) 下次检验时间 from b group by 产编) t
on 
      (a.产编=t.产编);