1

我正在尝试将增量计数添加到 2 个单独的字段。我有FieldAFieldB在同一张表中,需要像示例中那样增加 -

FieldA | ID1 | FieldB | ID2
ABC    | 1   | GREEN  | 2
ABC    | 1   | RED    | 3
ABC    | 1   | Yellow | 4
XYZ    | 5   | RED    | 6
DEF    | 7   | GREEN  | 8 
DEF    | 7   | BLUE   | 9

其中没有重复的数字,除了FieldA并且FieldA将根据 的最后一个而增加FIELDB

4

2 回答 2

0

没有一些行号似乎有点傻。我伪造了一个未在查询中显示的行号:

;with a as
(
select row_number() over (order by (select 1)) rn, FieldA, FieldB
from 
-- replace next row with your table
(values('ABC', 'GREEN'),('ABC', 'RED'),('ABC', 'Yellow'),('XYZ', 'RED'),('DEF', 'GREEN'),('DEF', 'BLUE')) t(FieldA, FieldB)
), b as
(
select  rn -  dense_rank() over (partition by fieldA order by rn) calc, rn, FieldA, FieldB from a
), c as
(
select FieldA,
calc+ dense_rank() over (order by calc) ID1,
FieldB, 
rn + dense_rank() over (order by calc) ID2 from b
)
select * from c

结果:

FieldA  ID1 FieldB  ID2
ABC     1   GREEN   2
ABC     1   RED     3
ABC     1   Yellow  4
XYZ     5   RED     6
DEF     7   GREEN   8
DEF     7   BLUE    9
于 2013-08-28T10:19:34.773 回答
0

对我来说很神秘,它在哪里有用。尽管如此:

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
于 2013-08-28T00:19:08.753 回答