sql - Find and update non duplicated record based on one of the column -
i want find non duplicated records , update 1 of column.
ex.
col_1 | col_2 | col_3 | col_4 | col_5     | aa    | bb    | 1     |      | ab    | bc    | 2     |     | ac    | bd    | 3     | b     | bb    | cc    | 1     | b     | bb    | cc    | 2     | c     | cc    | dd    | 1     |   my query has group col_1, , want find out not unique record based on col_2 , col3 , update col_5.
basically output should below,
col_1 | col_2 | col_3 | col_4 | col_5     | aa    | bb    | 1     | 1     | ab    | bc    | 2     | 1     | ac    | bd    | 3     | 1 b     | bb    | cc    | 1     | 0 b     | bb    | cc    | 2     | 0 c     | cc    | dd    | 1     | 0   does have idea how can achieve this? large database, performance key factor.
thanks heaps,
there plenty ways it. solution comes postgres have access to, bet working on tsql should have common syntax.
;with cte_1 (     select col_1 some_table group col_1 having count(*) > 1 ), cte_2 (     select col_1 some_table group col_1, col_2, col_3 having count(*) > 1 ), cte_3 (     select cte_1.col_1 cte_1     left join cte_2 on cte_1.col_1 = cte_2.col_1     cte_2.col_1 null ) update some_table set col_5 = 1 cte_3 cte_3.col_1 = some_table.col_1;   so, happens above?
first build 3 cte semi-tables allow split logic smaller parts:
cte_1extracts rows can have multiplecol2,col_3rowscte_2selects have non-uniquecol_2,col_3cte_3returnscol_1have uniquecol_2,col_3left join
using last
cte_3structure able updatesome_tablecorrectly
i assume table called some_table here. if you're worring performance should provide primary key here , have indexes on col_2 , col_3 (standalone may if composite on (col_1, col_2) , on).
also may want move cte use temporary tables (which indexed gain efficiency.
please note query works fine example without real data may guessing. mean happen when have col_1=a unique , non-uniqe col_2 in same time?
but believe it's point start.
Comments
Post a Comment