soozh
asked on
Delete unwanted rows
I have a table "TreatmentData" defined as:
create table #TreatmentData(
PatientId nvarchar(18),
TreatedWith nvarchar(30) );
The table lists patient treatments. A patient can have many rows in the table. There are six possible values for TreatedWith.
I need to delete all the patient records where the patient has "NoTreatment" for all his/her rows in the database. i.e. they have visited the clinic but not been treated.
I imagine it must be where the number of rows is equal to the count where the TreatedWith is "NoTreatment" when grouped by PatientId...
but i just can not get my head round it.
Any suggestions?
create table #TreatmentData(
PatientId nvarchar(18),
TreatedWith nvarchar(30) );
The table lists patient treatments. A patient can have many rows in the table. There are six possible values for TreatedWith.
I need to delete all the patient records where the patient has "NoTreatment" for all his/her rows in the database. i.e. they have visited the clinic but not been treated.
I imagine it must be where the number of rows is equal to the count where the TreatedWith is "NoTreatment" when grouped by PatientId...
but i just can not get my head round it.
Any suggestions?
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Just kidding: when you apply all the SQL statements against you treatment table that you have asked during last week, you will probably end up with a nice empty table. Ha-ha
delete from treatmentdata
where patientid in
(select patientid from treatmentdata where treatedwith = 'NoTreatment'
except
select patientid from treatmentdata where treatedwith <> 'NoTreatment')
where patientid in
(select patientid from treatmentdata where treatedwith = 'NoTreatment'
except
select patientid from treatmentdata where treatedwith <> 'NoTreatment')
Open in new window