SQL Server EXCEPTO
-
03-07-2019 - |
Pregunta
Aquí está la situación en la que me encuentro. Tengo una tabla con información de las personas. Algunos de ellos se importan desde otro sistema, mientras que otros se importan manualmente. Lo que me gustaría hacer es atraer a todos, pero si hay un registro ingresado manualmente y un registro que se importó, quiero seleccionar solo el importado (ya que es probable que esté más actualizado).
Esto es lo que tengo hasta ahora, pero no parece funcionar (solo devuelve los registros ingresados ??manualmente):
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
Tengo la sensación de que esto no está funcionando debido a que la consulta interna también está activando la columna de instype, pero no se me ocurren mejores formas de hacerlo. ¿Algún consejo?
Solución
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);
Otros consejos
puedes probar:
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
)