[英]How to compare two table values using PLSQL
我必須比較兩個表的值;
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編寫此代碼。
假設您僅考慮將類型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類型的唯一組合。
我在解釋您的意思是說,當TableB
包含3和7時,您要輸出'good'
;當它僅包含3時,您要輸出'avg'
,依此類推。 這是獲得此結果的一種方法:
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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.