根据表中的行和其他表更新表

时间:2018-12-07 15:19:14

标签: sql oracle

下面是我正在处理的表格-

table_ctrl_result-

seq_id  req_id  ctrl_id c1  c2  status
1       1       C001    DES 380 NULL
2       1       C001    ABC 0   NULL    
3       1       C001    EDC 0   NULL

TABLE_CTRL_MSTR-

ctrl_id tolerance   symbol
c001    1000        <

以下是预期结果,

seq_id  req_id  ctrl_id c1  c2  status
1       1       C001    DES 380 PASS
2       1       C001    ABC 0   PASS
3       1       C001    EDC 0   PASS

我正在使用评论中提到的多数民众赞成,但我得到了以下结果。

seq_id  req_id  ctrl_id c1  c2  status
1       1       C001    DES 380 PASS
2       1       C001    ABC 0   FAIL
3       1       C001    EDC 0   FAIL

SQL:

update ca_demo.table_ctrl_result a 
set a.STATUS = (
  select 
  (case 
   when b.symbol = '>' and a.c2 > b.tolerance or b.symbol = '<' and a.c2 < b.tolerance or b.symbol = '=' and a.c2 = b.tolerance 
   then 'PASS' 
   else 'FAIL' 
   end) 
  from ca_demo.table_ctrl_mstr b 
  where a.ctrl_id = b.ctrl_id 
); 

我想念一些东西。请协助。

1 个答案:

答案 0 :(得分:0)

测试用例:

SQL> create table ctrl_result
  2    (seq_id number,
  3     ctrl_id varchar2(4),
  4     c1 varchar2(3),
  5     c2 number,
  6     status varchar2(5));

Table created.

SQL> create table ctrl_mstr
  2    (ctrl_id varchar2(4),
  3     tolerance number,
  4     symbol varchar2(2));

Table created.

SQL> insert into ctrl_result
  2    select 1, 'C001', 'DES', 380, null from dual union all
  3    select 2, 'C001', 'ABC', 0,   null from dual union all
  4    select 3, 'C001', 'EDC', 0,   null from dual union all
  5    select 4, 'C002', 'XXX', 500, null from dual union all
  6    select 5, 'C002', 'YYY', 100, null from dual;

5 rows created.

SQL> insert into ctrl_mstr
  2    select 'C001', 1000, '<' from dual union all
  3    select 'C002', 200,  '>' from dual;

2 rows created.

一些查询和结果:

SQL> merge into ctrl_result c
  2    using (select r.seq_id, r.ctrl_id, r.c2,
  3                  m.tolerance, m.symbol,
  4                  --
  5                  case when m.symbol = '<' and r.c2 <  m.tolerance then 'PASS'
  6                       when m.symbol = '<' and r.c2 >= m.tolerance then 'FAIL'
  7                       when m.symbol = '>' and r.c2 >  m.tolerance then 'PASS'
  8                       when m.symbol = '>' and r.c2 <= m.tolerance then 'FAIL'
  9                       else 'NONE'
 10                  end status
 11           from ctrl_result r join ctrl_mstr m on m.ctrl_id = r.ctrl_id
 12          ) x
 13    on (c.seq_id = x.seq_id)
 14  when matched then update set c.status = x.status;

5 rows merged.

SQL> select * From ctrl_Result order by seq_id;

    SEQ_ID CTRL C1          C2 STATU
---------- ---- --- ---------- -----
         1 C001 DES        380 PASS
         2 C001 ABC          0 PASS
         3 C001 EDC          0 PASS
         4 C002 XXX        500 PASS
         5 C002 YYY        100 FAIL

SQL>