Quantcast
Channel: SQL.ru: Microsoft SQL Server
Viewing all articles
Browse latest Browse all 7251

Объединение дублей в группы

$
0
0
Исходные данные
declare @t table (rowId int identity(1,1)
, id int
, code nvarchar(100)
, name nvarchar(100)
, groupId int)
insert into @t (id, code, name)
select 1, 'A', '123' union all
select 1, 'A', 'ADC' union all
select 1, 'A', '001' union all
select 2, 'A', '123' union all
select 2, 'A', 'ABC' union all
select 2, 'A', '002' union all
select 4, 'A', '123' union all
select 5, 'A', 'ABC' union all
select 5, 'A', '005' union all
select 6, 'A', '005' union all
select 3, 'B', '456' union all
select 3, 'B', 'DFG' union all
select 3, 'B', '003'


нужен результат:
rowIdidcodenamegroupId
11A1231
21AADC1
31A0011
42A1231
52AABC1
62A0021
74A1231
85AABC1
95A0051
106A0051
113B4563
123BDFG3
133B0033


у меня получилось:
update t set t.groupId=x.id from @t t inner join (
select code, name, min(id) id
from @t
group by code, name
) x on t.code=x.code and t.name=x.name

update t set t.groupId=x.groupId from @t t inner join (
select id, min(groupId) groupId
from @t
group by id
) x on t.id=x.id

update t1 set t1.groupId=t2.groupId
from @t t1 inner join @t t2 on t1.code=t2.code and t1.name=t2.name
where t1.groupId > t2.groupId

update t1 set t1.groupId=t2.groupId
from @t t1 inner join @t t2 on t1.code=t2.code and t1.name=t2.name
where t1.groupId > t2.groupId

select * from @t


результат не тот. который нужен:
rowIdidcodenamegroupId
11A1231
21AADC1
31A0011
42A1231
52AABC1
62A0021
74A1231
85AABC1
95A0052
106A0052
113B4563
123BDFG3
133B0033

Viewing all articles
Browse latest Browse all 7251