后缀编号

时间:2014-06-29 19:34:48

标签: sql sql-server-2008-r2

我正在尝试使用后缀序列号对我的表中的记录(按家庭分组)重新编号,但跳过该系列中的第一条记录。我正在使用SQL mgmt studio 2008。

ID = record number
FamilyID = group identifier

Current Numbering

ID           FamilyID   Existing_Num
SM00000002  UIS00000693 UIS00000694
SM00000003  UIS00000693 UIS00000694
SM00000004  UIS00000693 UIS00000694
SM00000006  UIS00000882 UIS00000883
SM00000007  UIS00000882 UIS00000883
SM00000008  UIS00000882 UIS00000883
SM00000010  UIS00001057 UIS00001058
SM00000011  UIS00001057 UIS00001058
SM00000012  UIS00001057 UIS00001058
SM00000014  UIS00001193 UIS00001194
SM00000015  UIS00001193 UIS00001194
SM00000016  UIS00001193 UIS00001194
SM00000017  UIS00001193 UIS00001194
SM00000018  UIS00001193 UIS00001194
SM00000019  UIS00001193 UIS00001194
SM00000020  UIS00001193 UIS00001194
SM00000021  UIS00001193 UIS00001194

需要对当前编号进行后缀,以便显示以下内容:

ID              FamilyID    New_Num
SM00000002  UIS00000693 UIS00000694
SM00000003  UIS00000693 UIS00000694_001
SM00000004  UIS00000693 UIS00000694_002
SM00000006  UIS00000882 UIS00000883
SM00000007  UIS00000882 UIS00000883_001
SM00000008  UIS00000882 UIS00000883_002
SM00000010  UIS00001057 UIS00001058
SM00000011  UIS00001057 UIS00001058_001
SM00000012  UIS00001057 UIS00001058_002
SM00000014  UIS00001193 UIS00001194
SM00000015  UIS00001193 UIS00001194_001
SM00000016  UIS00001193 UIS00001194_002
SM00000017  UIS00001193 UIS00001194_003
SM00000018  UIS00001193 UIS00001194_004
SM00000019  UIS00001193 UIS00001194_005
SM00000020  UIS00001193 UIS00001194_006
SM00000021  UIS00001193 UIS00001194_007

这是我到目前为止的现有选择查询,导致我现有的表格:

select ID, FamilyID, 'UIS' + RIGHT('00000000' + CONVERT(VARCHAR,(SUBSTRING([MsgSort1],25,8) + 1)),8) AS Existing_num
from table_name

2 个答案:

答案 0 :(得分:2)

您可以尝试以下查询。我无法测试这个。但我们的想法是,您可以使用Row_Number函数来获取重复行的序列号。之后,您可以将序列号附加到现有的数字列。

;WITH table_cte(ID, FamilyID,Existing_num, seqNo)
AS
(
select ID, FamilyID, 
'UIS' + RIGHT('00000000' + CONVERT(VARCHAR,(SUBSTRING([MsgSort1],25,8) + 1)),8) AS Existing_num,
ROW_NUMBER() OVER (PARTITION BY ('UIS' + RIGHT('00000000' + CONVERT(VARCHAR,(SUBSTRING([MsgSort1],25,8) + 1)),8))) AS SeqNo
)
select ID, FamilyID, Existing_num, 
CASE WHEN seqNo = 1 THEN Existing_num
ELSE Existing_num + '_' + Right('000' + CONVERT(NVARCHAR, seqNo-1), 3)
END AS New_Num   
from table_name;

答案 1 :(得分:2)

这是Kiran Hegde的一个想法。我不会将其作为一个单独的答案发布,但解决方案中似乎还有很多事情要发布,并且所有评论似乎都指向了错误。所以,我决定分开发帖。在这里小提琴:http://sqlfiddle.com/#!3/a144c/9

WITH cteNumbered
AS
(
  SELECT    ID,
            FamilyID,
            (ROW_NUMBER() OVER (PARTITION BY FamilyID ORDER BY ID)) - 1 AS Suffix
  FROM      Table1
)

SELECT    ID,
          FamilyID,
          CASE 
            WHEN Suffix <> 0 THEN FamilyID + '_' + RIGHT('000' + CAST(Suffix AS VARCHAR(10)), 3)
            ELSE FamilyID
          END AS New_Num
FROM      cteNumbered
ORDER BY  ID,
          Suffix;