工作中偶尔有遇到这样的情况:比如说物料档案,编号不同但是名称或规格相同的有不少,如下例:
若需要对上图相同规格进行编号,比如A1、A2、B1、B2、B3……,该怎么处理呢?
为方便演示,先建立测试环境:
CREATE TABLE [dbo].[1TEST]( [ID] [int] IDENTITY(1,1) NOT NULL, [SPC] [varchar](50) NULL, CONSTRAINT [PK_1TEST] PRIMARY KEY CLUSTERED ( [ID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY] ) ON [PRIMARY] GO INSERT INTO [1TEST] (SPC) SELECT 'A' UNION ALL SELECT 'A' UNION ALL SELECT 'B' UNION ALL SELECT 'B' UNION ALL SELECT 'B' UNION ALL SELECT 'C' UNION ALL SELECT 'C' UNION ALL SELECT 'C' UNION ALL SELECT 'C' GO
处理的方法很简单,使用系统自动的函数ROW_NUMBER(),可以很快达成目的。
SELECT SPC,ROW_NUMBER() OVER (PARTITION BY SPC ORDER BY SPC) XH FROM [1TEST]
执行的结果如下: