如何每组增加一个字母

时间:2019-04-09 19:00:21

标签: sql-server character auto-increment

我有一个容器列表(超过2K行),我想将其分成多个比较

Code Name    Compartments
10   10 feet   1 
15   15 feet   1
25   25 feet   2
100  100 feet  3
150  150 feet  2

我这样做是为了实现这一目的

select * 
from Containers c
inner join master.dbo.spt_values b on b.type = 'P' and b.number < c.Compartments

获取

Code Name    Compartments
10   10 feet   1 
15   15 feet   1
25   25 feet   2
25   25 feet   2
100  100 feet  3
100  100 feet  3
100  100 feet  3
150  150 feet  2
150  150 feet  2

现在,我想在代码上添加一个自动递增的字母,但按这样的分组。

Code Name    Compartments
10A   10 feet   1 
15A   15 feet   1
25A   25 feet   2
25B   25 feet   2
100A  100 feet  3
100B  100 feet  3
100C  100 feet  3
150A  150 feet  2
150B  150 feet  2

我当时在考虑使用间隔数或添加一个标识列来添加anm增量char(64),但是我不知道如何使每组增量

select Code + CHAR(Compartments + 64), *  
from Containers c inner join master.dbo.spt_values b on b.type = 'P' and
b.number < c.Compartments

1 个答案:

答案 0 :(得分:0)

这对您有用,但请记住在26之后检查一下,这意味着当您到达“ Z”时会发生什么。

select Code + CHAR(ROW_NUMBER() OVER(PARTITION BY code ORDER BY name ASC) + 64), *  
from Containers c inner join master.dbo.spt_values b on b.type = 'P' and
b.number < c.Compartments