Search code examples
sql-serversql-server-2005except

SQL Server EXCEPT


Here's the situation I'm in. I have a table containing peoples' information. Some of them are imported from another system while some are imported manually. What I would like to do is pull everyone in, but if there is a record entered manually and a record that was imported, I want to select only the imported one (since it is likely more up to date).

Here is what I have so far, but it doesn't seem to work (it only returns the manually entered records):

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

I have a feeling this isn't working because of the inner query also pulling in the instype column, but I can't think of any better ways to do this. Any advice?


Solution

  •  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);