[英]Generate Alpha numeric series in SQL Server 2008
Can anyone please help me on this? 有人可以帮我这个吗?
I want to generate a alpha numeric series like A.1, A.2, A.3, A.4, B.1, B.2
which should increment automatically if I add new row. 我想生成一个字母数字系列,如A.1, A.2, A.3, A.4, B.1, B.2
,如果我添加新行A.1, A.2, A.3, A.4, B.1, B.2
它应自动增加。
I have a columns A and B which will be look like below. 我有一个A和B列,如下所示。
A B
-----
1 A
1 A
1 A
1 A
2 B
2 B
3 C
3 C
3 C
The result must be look like below: 结果必须如下所示:
A B C
-----------
1 A A.1
1 A A.2
1 A A.3
1 A A.4
2 B B.1
2 B B.2
3 C C.1
3 C C.2
3 C C.3
The below query can return your expected result. 以下查询可以返回您的预期结果。
SELECT A, B, B + '.' + CAST(ROW_NUMBER() OVER (PARTITION BY B ORDER BY A) AS VARCHAR) AS C
FROM TableName
Generating the Alpha numeric series is difficult. 生成Alpha数字系列很困难。 Using ROW_NUMBER()
in computed column is also not possible. 在计算列中使用ROW_NUMBER()
也是不可能的。 So for your case view
is the right choice to achieve your expectation: 因此,对于您的案例view
是实现您期望的正确选择:
CREATE VIEW dbo.vw_MyAlphaNumbericOrder AS
SELECT A, B, B + '.' + CAST(ROW_NUMBER() OVER (PARTITION BY B ORDER BY A) AS VARCHAR) AS C
FROM dbo.TableName
So when ever you are inserting a new record, then SELECT * FROM dbo.vw_MyAlphaNumbericOrder
will return with the alpha numeric series as column C
. 因此,当您插入新记录时, SELECT * FROM dbo.vw_MyAlphaNumbericOrder
将返回字母数字系列作为C
列。
Sample execution with the given sample data: 使用给定的样本数据执行示例:
DECLARE @TestTable TABLE (A INT, B VARCHAR (2));
INSERT INTO @TestTable (A, B) VALUES
(1, 'A'),
(1, 'A'),
(1, 'A'),
(1, 'A'),
(2, 'B'),
(2, 'B'),
(3, 'C'),
(3, 'C'),
(3, 'C');
SELECT A, B, B + '.' + CAST(ROW_NUMBER() OVER (PARTITION BY B ORDER BY A) AS VARCHAR) AS C
FROM @TestTable
We can achieve this by below statement: 我们可以通过以下声明来实现:
Select A,B,concat(B,'.',cast(row_number() over(partition by B order by B) as char(32))) as C
1.row_number() over (Partition by)-- will generate new row no. 1.row_number()over(Partition by) - 将生成新的行号。 in each category of column B. 2.Cast -- will change the numeric value to character value where 32 specifies the length of data the field can hold 3. Concat-- will concatenate the required columns to create Alpha-numeric string 在列B的每个类别中.2.Cast - 将数值更改为字符值,其中32指定字段可以容纳的数据长度3. Concat--将连接所需的列以创建字母数字字符串
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.