我想通过特定列创建一个序列组。
我有一个表LoanMaster
,还有一个名为BranchCode
的列。它有分支1 - 48.我想为每个分支生成一个序列号。与分支代码1一样,如果它有10条记录,则生成1到10的序列号,然后对于分支代码2,如果它有15条记录,则从1到15生成数字,依此类推。
怎么可能?
答案 0 :(得分:3)
使用ROW_NUMBER
:
SELECT
BranchCode,
[rn] = ROW_NUMBER() OVER(PARTITION BY BranchCode ORDER BY BranchCode)
FROM LoanMaster
ORDER BY BranchCode, rn
要从任意值开始,只需添加它:
<强> SqlFiddleDemo 强>
SELECT
BranchCode,
[rn] = ROW_NUMBER() OVER(PARTITION BY BranchCode ORDER BY BranchCode) + 100
FROM LoanMaster
ORDER BY BranchCode, rn
<强> Demo2 强>
CREATE TABLE #LoanMaster(Id INT, LeadsID1 INT, LBrCode INT);
INSERT INTO #LoanMaster(Id, LBrCode)
VALUES (1,1), (2,1), (3,1), (4,1), (5,2), (6,2), (7,2);
;WITH cte AS
(
SELECT
Id,
LBrCode,
[RowNumber] = ROW_NUMBER() OVER(PARTITION BY LBrCode ORDER BY LBrCode) + 2405
FROM #LoanMaster
)
UPDATE T1
SET LeadsID1=c.RowNumber
FROM #LoanMaster AS T1
JOIN cte c
ON c.LBrCode=T1.LBrCode
AND c.Id = T1.Id
WHERE c.LBrCode=1;
SELECT *
FROM #LoanMaster;
这是我的最后一次更新(接受是否接受答案),因为很久以前就回答了最初的问题:
在评论中写出越来越多的要求并不是SO的运作方式。