我有一组数据需要生成SetIds。基本上,如果我在第一个带有列ID顺序的数据集的位置,我希望每当我达到RecordType为5时都会增加一个计数器。请参阅所需输出的第二个样本。
Id RecordType Amount
----------------------------
1 5 1.00
2 6 1.00
3 7 3.00
5 5 1.00
6 6 .50
7 6 .50
8 8 1.00
9 5 .05
Id RecordType Amount SetId
-------------------------------------
1 5 1.00 1
2 6 1.00 1
3 7 3.00 1
5 5 1.00 2
6 6 .50 2
7 6 .50 2
8 8 1.00 2
9 5 .05 3
10 6 .05 3
答案 0 :(得分:0)
DECLARE @DataX TABLE (
Id INT IDENTITY
, RecordType INT
, Amount DECIMAL(5,2)
, SetId INT
)
INSERT INTO @DataX (RecordType, Amount) VALUES
(5,1)
, (6,1)
, (7,3)
, (5,1)
, (6,.5)
, (6,.5)
, (8,1)
, (5,.5)
; WITH SetId
AS (
SELECT Id, SUM (CASE WHEN RecordType = 5 THEN 1 ELSE 0 END) OVER (ORDER BY Id) AS SetId
FROM @DataX
)
UPDATE dx1
SET dx1.SetId = (SELECT SetId.SetId)
FROM @DataX dx1
JOIN SetId
ON dx1.Id = SetId.Id
SELECT * FROM @DataX
答案 1 :(得分:0)
您的初始样本数据缺少ID 10
DECLARE @Table Table (Id Int, RecordType Int, Amount Decimal(9,2))
Insert Into @Table (Id,RecordType,Amount) Values
(1,5,1),
(2,6,1),
(3,7,3),
(5,5,1),
(6,6,.5),
(7,6,.5),
(8,8,1),
(9,5,.05),
(10,6,.05)
Select *
,SetId = Sum(IIF(RecordType=5,1,0)) over (Order by ID)
From @Table
Order By Id
返回
Id RecordType Amount Flag SetId
1 5 1.00 1 1
2 6 1.00 0 1
3 7 3.00 0 1
5 5 1.00 1 2
6 6 0.50 0 2
7 6 0.50 0 2
8 8 1.00 0 2
9 5 0.05 1 3
10 6 0.05 0 3