tags:

views:

84

answers:

6

I've got the following table:

PatientID | DiagID

...where PatientID is a unique identifier and DiagID is a diagnosis ID, which is not unique. How do I delete the patient from table who's got unique DiagID (the only in the table, who's got this specific DiagID)?

A: 

A delete where clause doesn't have to use the primary key, example:

Delete From Table
Where DiagID = 5

If you mean you want to delete all uniques, then something like:

Delete From Table
Where DiagID In (Select DiagID
                 From Table
                 Group By DiagID
                 HAVING count(*) = 1)
Nick Craver
A: 

You say there's only one patient with this specific diagnosis id?

delete
from YourTable
where DiagID = @diagId
Aaron
A: 

If you know it is the only one then there is nothing wrong with this

DELETE FROM Patient 
WHERE DiagID = @inDiagID

If you want to be safe, something like this might be wise:

   IF NOT EXISTS(SELECT DiagID FROM Patient WHERE DiagID = @inDiagID GROUP BY DiagID HAVING COUNT(DiagID) = 1)
   BEGIN
          DELETE FROM Patient 
          WHERE DiagID = @inDiagID
   END
Hogan
A: 

Are you trying to delete patients that only have one DiagID?

DELETE FROM table
    WHERE PatientID IN 
    ( SELECT DiagID FROM table
    GROUP BY DiagID 
    HAVING COUNT(*) = 1)
ctrlShiftBryan
The subquery should throw an error: no aggregate on DiagID. Fix that, and then given PatientID is always unique, then COUNT(*) is always 1. TRUNCATE TABLE would be quicker. -1
gbn
oops yeah other have it correct
ctrlShiftBryan
A: 
DELETE
    D
FROM
    DiagTable D
    JOIN
    (SELECT DiagID FROM DiagTable D2 GROUP BY DiagID HAVING COUNT(*) = 1) foo ON D.DiagID = foo.DiagID

The subquery find unique (ie used once) DiagIDs. This is used to JOIN bak to delete rows for these unique DiagIDs

gbn
+1  A: 

Presumably you want to delete any patients that only have a single instance of a diagnosis ID. In which case the SQL would be something like:

DELETE Patient
WHERE DiagID in
(SELECT DiagID FROM Patient GROUP BY DiagID HAVING COUNT(*) = 1)
Chris Simpson