SQL Server EXCEPT
-
03-07-2019 - |
题
这就是我所处的情况。我有一张包含人们信息的表格。其中一些是从另一个系统导入的,而另一些是手动导入的。我想要做的就是吸引所有人,但是如果有手动输入的记录和导入的记录,我想只选择导入的记录(因为它可能更新)。
这是我到目前为止所做的,但它似乎不起作用(它只返回手动输入的记录):
SELECT --fields go here
FROM
(
SELECT PERSON_UID, instype
FROM AdmitsInterfaceTable
WHERE instype='M' --Manually entered people
EXCEPT
SELECT PERSON_UID, instype
FROM AdmitsInterfaceTable
WHERE instype='I' --Imported people
) P,
AdmitsInterfaceTable A
WHERE
P.PERSON_UID=A.PERSON_UID
AND P.instype=A.instype
我感觉这不起作用,因为内部查询也拉入了instype列,但我想不出更好的方法来做到这一点。有什么建议吗?
解决方案
SELECT PERSON_UID, instype
FROM AdmitsInterfaceTable a
WHERE instype='I' --get all imported people
union -- plus all manuals who are not also imported
SELECT PERSON_UID, instype
FROM AdmitsInterfaceTable a
WHERE instype='M' --Imported people
and not exists ( -- without imported matches
select * from FROM AdmitsInterfaceTable b
WHERE instype='I' and b.person_uid = a.person_uid);
其他提示
你可以尝试:
SELECT CASE WHEN b.person_UID is null THEN a.person_UID ELSE person_UID END,
CASE WHEN b.person_UID is null THEN a.instype ELSE instype END
--and so forth through all the columns you want
FROM
(SELECT PERSON_UID, instype -- add list of additional fields you need here
from AdmitsInterfaceTable WHERE instype='M' ) A
LEFT JOIN
(SELECT PERSON_UID, instype -- add list of additional fields you need here
from AdmitsInterfaceTable WHERE instype='I' ) B on A.PERSON_UID = B.PERSON_UID
SELECT --fields go here
FROM AdmitsInterfaceTable A
WHERE
P.PERSON_UID=A.PERSON_UID
AND P.instype=A.instype
AND instype='M' --Manually entered people
AND person_uid not in (
SELECT PERSON_UID FROM AdmitsInterfaceTable
WHERE instype='I' --Imported people
)
不隶属于 StackOverflow