开发者

Concatenated columns should not match in 2 tables

I'll just put this in layman's terms since I'm a complete noobie:

I have 2 tables A and B, both having 2 columns of interest namely: employee_number and salary.

What I am looking to do is to extract rows of 'combination' of employee_number and salary from A that are NOT present in B, but each of employee_number and salary should be present in both.

I am looking to doing it with the 2 following conditions(please forgive the wrong function names.. this is just to present the problem 'eloquently'):

1.) A.unique(employee_number) exists in B.unique(employee_number) AND A.unique(salary) exists in B.unique(salary)

2.) A.concat(employee_number,salary) <> B.concat(employee_number,salary)

Note: A and B are in different databases, so I'm looking to use dblink to do this.

This is what I tried doing:

SELECT distinct * FROM dblink('dbname=test1 port=5432 
        host=test01 user=user password=password','SELECT employee_number,salary, employee_number||salary AS ENS FROM empsal.A')
AS A(employee_number int8, salary integer开发者_开发技巧, ENS numeric)
LEFT JOIN empsalfull.B B on B.employee_number = A.employee_number AND B.salary = A.salary
WHERE A.ENS not in (select distinct employee_number || salary from empsalfull.B)

but it turned out to be wrong as I had it cross-checked by using spreadsheets and I don't get the same result.

Any help would be greatly appreciated. Thanks.


For easier understanding I left out the dblink. Because, the first one selects lines in B that equal the employeenumber in A as well as the salery in A, so their concatenated values will equal as well (if you expect this to not be true, please provide some test data).

SELECT * from firsttable A
LEFT JOIN secondtable B where 
    (A.employee_number = B.employee_number AND a.salery != b.salery) OR 
    (A.salery = B.salery AND A.employee_number != B.employee_number)

If you have troubles with lines containing nulls, you might also try somthing like this: AND (a.salery != b.salery OR (a.salery IS NULL AND b.salery IS NOT NULL) or (a.salery IS NOT NULL and b.salery IS NULL))


I think you're looking for something along these lines.

(Sample data)

create table A (
    employee_number integer primary key,
    salary integer not null
);

create table B (
    employee_number integer primary key,
    salary integer not null
);

insert into A values 
(1, 20000),
(2, 30000),
(3, 20000);  -- This row isn't in B

insert into B values
(1, 20000),  -- Combination in A
(2, 20000),  -- Individual values in A
(3, 50000);  -- Only emp number in A

select A.employee_number, A.salary
from A
where (A.employee_number, A.salary) NOT IN (select employee_number, salary from B)
  and  A.employee_number IN (select employee_number from B)
  and  A.salary IN (select salary from B)

output: 3, 20000

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜