Question

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)?

Was it helpful?

Solution

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)

OTHER TIPS

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)

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

delete
from YourTable
where DiagID = @diagId
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

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)

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top