【问题标题】:Oracle SQL select loop based on other select基于其他选择的 Oracle SQL 选择循环
【发布时间】:2012-08-15 09:22:58
【问题描述】:

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

我正在尝试做的一些伪代码(我将如何在 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;

提前致谢!

【问题讨论】:

    标签: sql oracle select loops for-loop


    【解决方案1】:

    只需将表连接到自身(使用 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;
    

    请注意,出于(在我看来)明显的原因,我将网格位置添加到 group by 和 select 子句 - 如果不清楚,您可以作为单独的问题提出。

    【讨论】:

    • 嗨 DVK。你能解释一下这是怎么写给我的吗?我对 SQL 很陌生...您是否根据我的原始表“MYTABLE”创建了一对临时表(1 和 2)?当我运行这个插入正确的表名和数据中心时,我收到以下错误:ORA-01747: invalid user.table.column, table.column, or column specification。谢谢。
    【解决方案2】:

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

    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;
    

    【讨论】:

    • 嗨,戈登,我绝对可以按照你的逻辑来编写它,但是当我尝试运行它时出现错误(我替换了正确的表名和数据中心名称):@987654322 @。关于错误可能在哪里的任何想法?
    • @nvrmore100 。 . .我遗漏了一个“和”声明。当我采用别人的缩进样式时,我更容易出现这样的错误。那好吧。这应该可以解决语法问题。
    猜你喜欢
    • 1970-01-01
    • 2021-02-04
    • 2021-09-25
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 2014-10-18
    • 2012-02-26
    • 1970-01-01
    相关资源
    最近更新 更多