Mega Query中的子查询

时间:2017-05-31 12:28:03

标签: oracle

我搜索过,但找不到符合我需要的例子。也许我迷失在我的查询的许多连接中......

我从三个Oracle 11g表中返回数据 - ATE_TESTS,ATE_DATA和TM_CONDITION_DYNAMIC。该查询还有其他表来加入这些表。事实上,有不少于7个连接。

ATE_DATA可能在连接的Many侧有多条记录,但我只想要最后写的行。 ATE_DATA有一个递增的主键,我想在子查询中的聚合函数MAX(DATA_PK)中使用它。我认为它应该在主查询的WHERE子句中,但我不知道如何实现它,可能有更好的方法。

也许我可能受过教育?

我的查询是:

SELECT ate_serial, data_data, dyn_value
FROM   ate_tests
       LEFT JOIN ate_test_procedure
         ON ate_tests.ate_pk = ate_test_procedure.proc_ate_test_fk
       LEFT JOIN ate_test_data
         ON ate_test_procedure.proc_pk = ate_test_data.data_ate_test_procedure_fk
       LEFT JOIN tm_test_procedure
         ON ate_test_procedure.proc_test_procedure = tm_test_procedure.proc_pk
       LEFT JOIN tm_test_specification
         ON ate_test_data.data_specification = tm_test_specification.spec_pk
       LEFT JOIN tm_test_condition_dynamic
         ON tm_test_specification.spec_condition_set_fk = tm_test_condition_dynamic.dyn_condition_set_fk
       LEFT JOIN tm_test_sequences
         ON ate_tests.ate_sequence_fk = tm_test_sequences.seq_pk
       LEFT JOIN lu_tm_products_model
         ON tm_test_sequences.seq_model = lu_tm_products_model.lumod_pk
WHERE  upper(spec_name) = 'POWER'
AND    lumod_model = 'AMP'
AND    dyn_value = '136'
AND    ate_yield = 1
AND    upper(proc_procedure_name) = 'FINAL TEST'
AND    proc_report = 1
AND    proc_status = 1
ORDER BY ate_serial, dyn_value

1 个答案:

答案 0 :(得分:0)

  

...但我只想写最后一行。

这是典型的前n个查询。我们假设表a包含有关蔬菜的信息,表b表示不同商店的历史价格以及s有关这些商店的信息。您只对最后价格感兴趣, 你可以使用函数row_number()(或max() ... keep dense rank last...)找到它。

with a as (select 1 vid, 'Tomato' name from dual union all
           select 2 vid, 'Potato' name from dual union all
           select 3 vid, 'Garlic' name from dual),

     b as (select 1 pid, 1 vid, 1 sid, 11.5 price from dual union all 
           select 2 pid, 3 vid, 1 sid, 31.8 price from dual union all
           select 3 pid, 1 vid, 1 sid, 13.2 price from dual union all
           select 4 pid, 1 vid, 2 sid, 12.7 price from dual ),

     s as (select 1 sid, 'Best Vegetables'  name from dual union all
           select 2 sid, 'Organic Products' name from dual)

select a.vid, a.name, s.name as shop, p.price as last_price
  from a 
    left join (select vid, sid, price 
                 from (select vid, sid, price, 
                              row_number() over (partition by vid order by pid desc) rn 
                         from b)
                 where rn = 1) p
      on p.vid = a.vid
    left join s on s.sid = p.sid
  order by a.vid

输出:

VID  Name      Shop                Price
---  --------  ------------------  -------
  1  Tomato    Organic Products       12.7
  2  Potato
  3  Garlic    Best Vegetables        31.8