compare from different table inside case statement

时间:2018-08-22 13:45:06

标签: sql

I am struggling with a use case and any help is appreciated.
I need to do through SQL and no other programming language.Use case is below explained.
I have two table :

TABLE 1:

name code_1 code_2
abc  234    
abc  123   234
xyz        345

TABLE 2:

name code rank
abc 234   1
abc 456   2
xyz 345   1
xyz 678   2

So i have two table and i need to check whether the population in the TABLE 1 column code_1 and code_2 is correct or not.

table1 has three coloumns with first column as name ,second column having default value and third column name is derived using the table 2.

table 2 is majorly a look up table which has three column namely name same as above table ,second column is code and third column is rank.

I need to create a query to check whether the population made in table 1 is correct or not.

Rules for population:

  1. if for a name, code 1 in table 1 is null,take rank 1 from look up table(table2 )for that name in the code 2 column.

  2. if for a name code 1 is populated and is not in the list of code as per table 2 for that name then populate rank 1 from table 2 in code 2 column.

  3. if code 1 is correct then leave it as it is and nothing should go to code 2 in table 1.

2 个答案:

答案 0 :(得分:0)

I would summarize the second table and do a comparison. Something like this:

select name,
       (case when count(*) = 1 and max(which) = 1 then 'Only in table1'
             when count(*) = 1 and max(which) = 2 then 'Only in table2'
             when (max(code_1_1) = max(code_1_2) or max(code_1_1) is null and max(code_1_2) is null) and
                  (max(code_2_1) = max(code_2_2) or max(code_2_1) is null and max(code_2_2) is null)
            then 'Same'
             else 'Different'
        end) as which,
       max(code_1_1), max(code_1_2), max(code_2_1), max(code_2_2)
from ((select name, code_1_1, code2_2, null as code_1_2, null as code_2_2, 1 as which
       from table1
      ) union all
      (select name, null, null, max(case when rank = 1 then code end), max(case when rank = 2 then code end), 2
       from table2
       group by name
      )
     ) tt
group by name;

答案 1 :(得分:0)

我没有检查您的数据,但是应该这样做:

update Table1 
set code_2=t2.Code
from Table1 t1 inner join Table2 t2
on  t1.name=t2.name and t2.rank=1
where t1.Code_1 is null

update Table1 
set code_2=t2.Code
from Table1 t1 inner join Table2 t2
on  t1.name=t2.name and t2.rank=1
where t1.Code_1 is not null 
    and t1.Code_1 not in 
    (select  Code from Table2)