I have a query that will run and allow me to find out if i have persons in the DB with more than one active account number. I was trying to setup this query to delete the additional accounts other than the one i specify i wanted to keep. The query is below, (the database layout is a lesson in relational db's and data is in multiple tables.
select c.id_value as Account_number, c.identifierdomain_key, d.id_value as Medical_Record_Number, a.admit_time, a.last_update_time, b.given_name as First_Name, b.family_name as Last_Name, l.nursing_unit as HIS_unit, l.bed as HIS_room_bed, l.encounterlocation_key, a.patient_key, a.encounter_key from encounter as a
inner join personname as b on a.patient_key = b.person_key
inner join encounteridentifier as c on a.encounter_key = c.encounter_key
inner join personidentifier as d on a.patient_key = d.person_key
inner join encounterlocation as l on a.assigned_location = l.encounterlocation_key
where a.patient_key in (select patient_key from encounter as a
group by a.patient_key
having count(a.patient_key) > 1 and d.id_value = '000000109')
order by last_name;
output of the query when i add this code below i get an error at the if line, i do have a secondary query that i can run that is the basis of the delete from lines where i pull the key values and that works. Just trying to make something iterate though and remove but cannot seem to link the two queries together as one
**if c.id_value != '12342'**
**delete from ccg.ccg.encounter cascade**
**where account_key = a.encounter_key;**
**delete from ccg.ccg.account cascade**
**where account_key = a.encounter_key;**
**delete from ccg.ccg.encounterlocation**
**where encounttion cascadeerlocation_key = l.encounterlocation_key;**
**delete from ccg.ccg.identifierdomain cascade**
**where identifierdomain_key = c.identifierdomain_key;**
** end if**
sort of stuck trying to figure out how to take actions on the results of my select statement to automate this process where i have the datapoints just cannot link them together
encounter? Postgres version? Actually, we'd need to see most of your relational design, to get the query right. What'sccg.ccg.encountersupposed to be? That's an illegal name for a table.if c.id_value != '12342'cannot work afterselect c.id_value as Account_number. You say you want to "delete the additional accounts" , but then you show deletes from 4 distinct tables. Why isand d.id_value = '000000109'in the subquery expression? I don't think you intend to do exactly what this does, but then it's not clear what exactly you are trying to do.ifis not valid SQL (it's supported in PL/pgSQL but that is only applicable in function blocks).