基于其他select的Oracle SQL select循环

时间:2012-08-14 23:02:23

标签: sql oracle select loops for-loop

我想根据初始select语句返回的值执行一系列select语句。基本上循环遍历原始值并使用该值作为新选择的条件。

我想要做的一些伪代码(我将如何在shell中写这个...):

for location in `select places from tablename where XYZ`
do
   select new_field from tablename where location = '$location';
done

以下是我真正想要的选择。

给我一​​个机架列表:

select   regexp_substr("MYTABLE"."Serial_Number" ,'[^ ]+', 1, 3) as "Racks"
  from   "MYTABLE" "MYTABLE" 
 where   "MYTABLE"."Data_Center" ='SOMEPLACE' 
   and   "MYTABLE"."Device_Type" ='RACK'
   and   "MYTABLE"."Serial_Number" not like '%WAREHOUSE%'

根据设备数量打印谁应该拥有机架:

select count(*) as count, LOB 
 from    "MYTABLE" "MYTABLE" 
 where   "MYTABLE"."Data_Center" ='SOMEPLACE' 
   and   GRID_LOCATION = '$RACK_from_above' and rownum <= 1 group by LOB order by count desc;

提前致谢!

2 个答案:

答案 0 :(得分:2)

只需将表格连接到自身(使用2个不同的别名)

select count(1) as count, MYTABLE1.LOB, MYTABLE1.GRID_LOCATION  
from    "MYTABLE" "MYTABLE1" , "MYTABLE" "MYTABLE2"   
where   MYTABLE1.Data_Center ='SOMEPLACE'    
 and   MYTABLE1.GRID_LOCATION = regexp_substr(MYTABLE2.Serial_Number ,'[^ ]+', 1, 3)
 and   MYTABLE1.rownum <= 1
 and   MYTABLE2.Data_Center ='SOMEPLACE'
 and   MYTABLE2.Device_Type ='RACK'
 and   MYTABLE2.Serial_Number not like '%WAREHOUSE%'
group by MYTABLE1.LOB, MYTABLE1.GRID_LOCATION
order by count desc;

请注意,我在网格位置添加了网格位置并选择了(在我看来)显而易见的原因的条款 - 如果不清楚,您可以单独提问。

答案 1 :(得分:0)

您可以轻松地将这些组合成一个查询:

with thelist as (
    select   regexp_substr("MYTABLE"."Serial_Number" ,'[^ ]+', 1, 3) as "Racks"
      from   "MYTABLE" "MYTABLE" 
     where   "MYTABLE"."Data_Center" ='SOMEPLACE' 
       and   "MYTABLE"."Device_Type" ='RACK'
       and   "MYTABLE"."Serial_Number" not like '%WAREHOUSE%'
)
select count(*) as count, LOB 
from    "MYTABLE" "MYTABLE" 
where   "MYTABLE"."Data_Center" ='SOMEPLACE' and
      GRID_LOCATION in (select racks from thelist) and
      rownum <= 1
group by LOB
order by count desc;