sql server - Merge multiple rows in SQL with tie breaking on primary key -
i have table data following
key | | b | c --------------------------- 1 | x | 0 | 1 2 | x | 2 | 0 3 | x | null | 4 4 | y | 7 | 1 5 | y | 3 | null 6 | z | null | 4
and want merge rows based on column largest primary key being 'tie breaker' between values not null
result key | | b | c --------------------------- 1 | x | 2 | 4 2 | y | 3 | 1 3 | z | null | 4
what best way achieve assuming data 40 columns , 1 million rows unknown level of duplications?
using row_number
, conditional aggregation:
with cte as( select *, rnb = row_number() over(partition order case when b null 0 else 1 end desc, [key] desc), rnc = row_number() over(partition order case when c null 0 else 1 end desc, [key] desc) tbl ) select [key] = row_number() over(order a), a, b = max(case when rnb = 1 b end), c = max(case when rnc = 1 c end) cte group
Comments
Post a Comment