对我来说很神秘,它在哪里有用。尽管如此:
declare @table table (FieldA varchar(50), FieldB varchar(50))
insert into @table values
('ABC','GREEN')
,('ABC','RED')
,('ABC','Yellow')
,('XYZ','RED')
,('DEF','GREEN')
,('DEF','BLUE')
;with [1](fa) as (select distinct FieldA from @table),
[2](fa, id1) as (select fa, row_number() over (order by fa) from [1]),
[3](fa, fb, id2) as (select FieldA, FieldB, row_number() over (partition by FieldA order by FieldB) from @table),
[4](id1, id2, fa, fb, p) as (
select NULL, id1, fa, NULL, cast(id1 as binary(4)) from [2]
union all
select [2].id1, [3].id2, [2].fa, [3].fb, cast([2].id1 as binary(4)) + cast([3].id2 as binary(4))
from [2] join [3] on [3].fa = [2].fa),
[5] as (select id1, id2, fa, fb, rn=row_number() over (order by p) from [4])
select t.FieldA, [6].rn as ID1, t.FieldB, [7].rn as ID2
from @table t
join [5] [6] on [6].fa = t.FieldA and [6].fb is NULL
join [5] [7] on [7].fa = t.FieldA and [7].fb = t.FieldB
输出是(与您指定的不完全一样,但如果没有一些标识符来排序,它就不能准确):
FieldA ID1 FieldB ID2
-------- ---- -------- -----
ABC 1 GREEN 2
ABC 1 RED 3
ABC 1 Yellow 4
DEF 5 BLUE 6
DEF 5 GREEN 7
XYZ 8 RED 9