sql server delete duplicate records from a table after checking if these records are there in dependent table -


i have 2 tables below

table_1
app_med_chip_id   application_id    person_id
248340                     1228144                   1028940
248342                     1228144                   1028940

328526                   1273218                   818905
328527                   1273218                   1386405
328528                   1273218                   1386407

table_2
app_med_chip_detail_id    app_med_chip_id
92574                                        248342

in table 1 first 2 records duplicates have same application_id , person_id, need take app_med_chip_id (248340,248342) of these 2 records, check if these present in table 2, delete record table 1 not present in table 2.

i have used below query select duplicates.

select * <br> (select row_number() on (partition application_id,person_id order application_id,person_id) row,*  table_1) p<br> p.app_med_chip_id not in<br>  (select app_med_chip_id table_2)<br> , p.row > 1 

problem query first set of records in table_1, result set not show first set of records used condition p.row > 1, if not use condition not able filter duplicates.

i have shown 2 sets of records example, there many other records in table_1 this.

please advise on how solve this.

thank you.

delete record table 1 not present in table 2

so, think want delete "duplicate" rows in table_1 not exist in table_2. want delete rows when there more record when grouped application_id , person_id.

you this:

delete table_1 app_med_chip_id not in (     select app_med_chip_id table_2 ) , exists (     select 1 table_1 t1     table_1.application_id = t1.application_id        , table_1.person_id = t1.person_id     having count(*) > 1 ) 

of course, root issue dirty data allowed in table_1. if have control on ddl, put constraint on table_1, such fk table_1.app_med_chip_id references table_2.app_med_chip_id or unique constraint on table_1 columns (application_id, person_id). if not have control on ddl, feel you.


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

jsf - How to ajax update an item in the footer of a PrimeFaces dataTable? -

django - CSRF verification failed. Request aborted. CSRF cookie not set -