我正在尝试将增量计数添加到2个单独的字段中。
我在同一个表中有FieldA
和FieldB
,需要按示例中的方式递增 -
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
的最后一个。
答案 0 :(得分: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
答案 1 :(得分:0)
如果没有一些row_number,似乎有点傻。我伪造了一个我在查询中没有显示的行号:
;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