为重复的客户端生成行号-SQL

时间:2019-01-16 22:09:13

标签: sql sql-server

我有一个简单的基于row_number的查询,并没有为我带来所需的结果:

create table #fake(client_id int)
insert #fake
values(1991) ,(1991),(1992)

select distinct
    _row_ord = 100,
    _client_id =  c.client_id,
    _segment = 'fake',
    --_row = row_number() over(order by c.client_id)
    _value = 
        concat
                (
                'HL*',
                row_number() over(order by c.client_id) + 1 ,'*',
                'testfield','~' 
                )
from #fake c 

drop table #fake

所以我当前的输出是:

enter image description here

所需的输出:

enter image description here

我意识到我的row_number查询缺少某些内容。有帮助吗?

1 个答案:

答案 0 :(得分:3)

row_number()更改为dense_rank()以获得所需的结果:

select distinct
    _row_ord = 100,
    _client_id =  c.client_id,
    _segment = 'fake',
    --_row = row_number() over(order by c.client_id)
    _value = 
        concat
                (
                'HL*',
                dense_rank() over(order by c.client_id) + 1 ,'*',
                'testfield','~' 
                )

结果:

_row_ord    _client_id  _segment    _value
100         1991        fake        HL*2*testfield~
100         1992        fake        HL*3*testfield~

See a live demo on rextester.