ID DEPT
user1 A
user1 B
user1 C
user2 A
user2 B
user3 A
user4 A
user4 B
user4 D
user4 E
我想拿一张像上面这样的表,看看哪些用户有部门A但没有C,然后插入C,反之亦然(有C,不是A,用A插入新行)
例如,在上表中,User4 将被标识为具有 A 而不是 C,因此将插入具有 user4 和部门 C 的新行。
INSERT INTO tablename(Id, Dept)
SELECT COALESCE(A.ID, C.ID)
, CASE
WHEN A.ID IS NULL THEN 'A'
WHEN C.ID IS NULL THEN 'C'
END
FROM
(select id
from tableName
WHERE Dept = 'A') A
FULL OUTER JOIN
(select id
from tableName
WHERE Dept = 'C') C
ON A.Id = C.Id
WHERE
A.Id IS NULL OR C.Id IS NULL