我使用字段LastName的前三个字符生成字母数字ID,然后使用递增的3位数字。我在MSSQL 2012中使用的查询是:
SELECT LastName, FirstName,
UPPER(LEFT(LastName, 3)) + LEFT('000', LEN(ROW_NUMBER()
OVER (PARTITION BY LEFT(LastName, 3)ORDER BY LEFT(LastName, 3)) )+1)
+ CAST(ROW_NUMBER() OVER (PARTITION BY
LEFT(LastName, 3)ORDER BY LEFT(LastName, 3)) AS NVARCHAR(1000)) AS ID
FROM @Table
查询工作相对较好但是一旦数字增加到2而不是结束010,它就是00010.一旦数字部分增加到三位数,情况也是如此。例如,我想要一个如下输出:
╔══════════╦═══════════╦══════════╗
║ LastName ║ FirstName ║ ID ║
╠══════════╬═══════════╬══════════╣
║ Jones ║ David ║ JON001 ║
║ Jones ║ David ║ JON002 ║
║ Jones ║ David ║ JON003 ║
║ Jones ║ David ║ JON004 ║
║ Smith ║ John ║ SMI001 ║
║ Smith ║ John ║ SMI002 ║
║ Smith ║ Robert ║ SMI003 ║
║ Smith ║ John ║ SMI004 ║
║ Smith ║ John ║ SMI005 ║
║ Smith ║ Robert ║ SMI006 ║
║ Smith ║ John ║ SMI007 ║
║ Smith ║ John ║ SMI008 ║
║ Smith ║ Robert ║ SMI009 ║
║ Smith ║ John ║ SMI010 ║
║ Smith ║ John ║ SMI011 ║
║ Smith ║ Robert ║ SMI012 ║
║ .. ║ .. ║ .. ║
║ Smith ║ James ║ SMI100 ║
╚══════════╩═══════════╩══════════╝
我不确定如何处理递增的数字字段。感谢您提供的任何帮助。
答案 0 :(得分:1)
从右边而不是左边?
SELECT *, UPPER(LEFT(LastName, 3)) + RIGHT('000' + CAST(ID AS VARCHAR(3)), 3)
FROM (
SELECT
LastName,
FirstName,
ROW_NUMBER() OVER (PARTITION BY LEFT(LastName, 3) ORDER BY LastName) AS ID
FROM @table
) T