views:

103

answers:

3
+1  Q: 

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?

+1  A: 
 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);
tpdi
A: 

you could try:

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
HLGEM
A: 
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
)
BlackTigerX