从三个不同的查询中获取最大数量

时间:2012-07-19 13:18:44

标签: sql oracle

我有3个查询,根据条件检索最大值。

select max(to_number(substr(attr_value,9)))+1 
  from circ_inst inner
  join circ_attr_settings 
    on circ_inst.circ_inst_id=circ_attr_settings.circ_inst_id 
   and val_attr_inst_id=1045 
 where circ_attr_settings.attr_value like 'IPANEMA-%' 



select max(to_number(substr(attr_value,10)))+1 
  from circ_inst inner
  join circ_attr_settings 
    on circ_inst.circ_inst_id=circ_attr_settings.circ_inst_id 
   and val_attr_inst_id=1045 
 where circ_attr_settings.attr_value like 'FIREWALL-%'



select max(to_number(substr(attr_value,16)))+1 
  from circ_inst 
 inner join circ_attr_settings
    on circ_inst.circ_inst_id=circ_attr_settings.circ_inst_id
   and val_attr_inst_id=1045 
 where circ_attr_settings.attr_value like 'LAYER2 SWITCH-%'

我想从这3个查询中获取最大数量(如果3个查询的结果分别是6430,6434和6418,那么我想获得值“6434”,这是三个中的最大值结果

我尝试使用max(query1,query2,query3)但未成功。

2 个答案:

答案 0 :(得分:5)

我认为您可以使用一个查询执行此操作:

select max(to_number(substr(attr_value,instr(attr_value, '-')+1)))+1
from circ_inst inner join
     circ_attr_settings
     on circ_inst.circ_inst_id=circ_attr_settings.circ_inst_id and
        val_attr_inst_id=1045
where circ_attr_settings.attr_value like 'LAYER 2 SWITCH-%') or
      circ_attr_settings.attr_value like 'IPANEMA-%' or
      circ_attr_settings.attr_value like 'FIREWALL-%'

你的联盟似乎都是一样的。唯一的区别是提取数字。您可以通过在值中查找“ - ”来获得正确的起始位置。

答案 1 :(得分:2)

你也许可以这样做:

select greatest (
(select max(to_number(substr(attr_value,9)))+1 from circ_inst inner join circ_attr_settings on circ_inst.circ_inst_id=circ_attr_settings.circ_inst_id and val_attr_inst_id=1045 where circ_attr_settings.attr_value like 'IPANEMA-%'),
(select max(to_number(substr(attr_value,10)))+1 from circ_inst inner join circ_attr_settings on circ_inst.circ_inst_id=circ_attr_settings.circ_inst_id and val_attr_inst_id=1045 where circ_attr_settings.attr_value like 'FIREWALL-%'),
(select max(to_number(substr(attr_value,16)))+1 from circ_inst inner join circ_attr_settings on circ_inst.circ_inst_id=circ_attr_settings.circ_inst_id and val_attr_inst_id=1045 where circ_attr_settings.attr_value like 'LAYER 2 SWITCH-%')
) from dual;