Исходные данные
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'
нужен результат:
rowId | id | code | name | groupId | 1 | 1 | A | 123 | 1 | 2 | 1 | A | ADC | 1 | 3 | 1 | A | 001 | 1 | 4 | 2 | A | 123 | 1 | 5 | 2 | A | ABC | 1 | 6 | 2 | A | 002 | 1 | 7 | 4 | A | 123 | 1 | 8 | 5 | A | ABC | 1 | 9 | 5 | A | 005 | 1 | 10 | 6 | A | 005 | 1 | 11 | 3 | B | 456 | 3 | 12 | 3 | B | DFG | 3 | 13 | 3 | B | 003 | 3 |
|
у меня получилось:
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
результат не тот. который нужен:
rowId | id | code | name | groupId | 1 | 1 | A | 123 | 1 | 2 | 1 | A | ADC | 1 | 3 | 1 | A | 001 | 1 | 4 | 2 | A | 123 | 1 | 5 | 2 | A | ABC | 1 | 6 | 2 | A | 002 | 1 | 7 | 4 | A | 123 | 1 | 8 | 5 | A | ABC | 1 | 9 | 5 | A | 005 | 2 | 10 | 6 | A | 005 | 2 | 11 | 3 | B | 456 | 3 | 12 | 3 | B | DFG | 3 | 13 | 3 | B | 003 | 3 |
|