ID DEPT
user1 A
user1 B
user1 C
user2 A
user2 B
user3 A
user4 A
user4 B
user4 D
user4 E
我想拿一个如上所示的表,查看哪些用户有de而不是C,插入C,反之亦然(有C,不是A,用A插入新行)
在上面的表中,例如,User4将被识别为具有A而不是C,因此将插入具有user4和dept C的新行。
答案 0 :(得分:0)
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