如何使用PLSQL比较两个表值

时间:2014-02-20 21:56:08

标签: sql oracle join

我必须比较两个表值;

TABLE_A     TABLE_B 

ID  TYPE    ID  TYPE
12345       12345   3
67891       12345   7
36524       67891   3
            67891   2
            67891   5
            36524   3

逻辑:我必须将table_A id与Table_B id

进行比较

如果发现3& 7          好 否则只发现3          平均 否则如果发现只有7          坏

这些好,坏和平均值应该回到表A类型值。

任何人都可以帮助我如何在PLSQL中编写这段代码。

2 个答案:

答案 0 :(得分:1)

假设您只考虑类型3和7进行计算,可以使用以下合并语句,不需要PL-SQL

merge into table_a a
using (select id, case (listagg(type, ',') within group (order by type))
                    when '3,7' then 'Good'
                    when '3'   then 'Avg'
                    when '7'   then 'Bad'
                    else null
                  end new_type
         from table_b
        where type in (3,7)
       group by id) b
   on (a.id = b.id)
 when matched then
   update set type = new_type;

对于11 g版本2之前的Oracle版本,请使用以下命令:

merge into table_a a
using (select id, case (trim(both ',' from min(decode(type, 3, 3, null))||','||min(decode(type, 7, 7, null))))
                when '3,7' then 'Good'
                when '3'   then 'Avg'
                when '7'   then 'Bad'
                else null
              end new_type
     from table_b
    where type in (3,7)
   group by id) b
   on (a.id = b.id)
 when matched then
   update set type = new_type;

假设table_b中存在唯一的id类型组合。

答案 1 :(得分:0)

我正在解释你的意思是说当'good'同时包含3和7时要输出TableB'avg'只包含3,依此类推。以下是获得此结果的方法:

select a.id,
       (case when sum(case when b.type = 3 then 1 else 0 end) > 1 and
                  sum(case when b.type = 7 then 1 else 0 end) > 0
             then 'good'
             when sum(case when b.type = 3 then 1 else 0 end) > 1
             then 'avg'
             when sum(case when b.type = 7 then 1 else 0 end)
             then 'bad'
        end) as logic
from tableA a left outer join
     tableB b
     on a.id = b.id
group by a.id;