プレフィックスが 1 文字の長さであると仮定すると、次のことを試すことができます。
;with cte as (
select type, typePrefix = left(no, 1), typeNum = right(no, len(no) - 1)
from TableName
)
select typePrefix + cast(isnull(max(typeNum), 0) + 1 as varchar(10))
from cte
where type = 'type1'
group by typePrefix
no
ただし、テーブルにない型 (たとえば「type4」) に対してnext を生成しようとすると、機能しません。それを可能にするには、各タイプのプレフィックスが指定されている別のテーブルが必要になる場合があります。
create table TypePrefixes (type varchar(50), prefix varchar(10))
insert into TypePrefixes values ('type1', 'a')
insert into TypePrefixes values ('type2', 'b')
insert into TypePrefixes values ('type3', 'c')
insert into TypePrefixes values ('another_type', 'd')
--etc.
この場合、次に取得するステートメントは次のno
ようになります。
select tp.prefix + cast(isnull(max(cast(right(t.no, len(t.no) - len(tp.prefix)) as int)), 0) + 1 as varchar(20))
from TableName t
right join TypePrefixes tp on tp.type = t.type
where tp.type = 'type4'
group by tp.prefix
no
また、次のように、その場で各レコードを計算したい場合もあります。
;with cte as (
select *,
typeNum = row_number() over (partition by type order by id),
typePrefix = char(dense_rank() over (order by type) + ascii('a') - 1)
from TableName
)
select *, No2 = typePrefix + cast(typeNum as varchar(10))
from cte
ただし、後者は、テーブル内の個別の型の数が制限されているため、26 を超えてはなりません (「z」を超えないようにするため)。