我有一个看起来像这样的SQL Server表(ID是PK标识字段)
ID Date Condition Call_Count
1 2015-03-02 14:05:05 Terminated 0
2 2015-03-02 14:05:10 Transferred 0
3 2015-03-02 14:06:02 Transferred 0
4 2015-03-02 14:07:00 Transferred 0
5 2015-03-02 14:07:50 Terminated 0
6 2015-03-02 14:07:60 Transferred 0
7 2015-03-02 14:08:55 Terminated 0
8 2015-03-02 14:08:56 Terminated 0
我试过以下内容:
DECLARE @LoopId INT = 1,
@Call_Count INT = 1,
@callend INT,
@maxId INT,
@LoopCounter INT
Select @MaxId = max(ID) from Table1
WHILE(@LoopId <= @MaxId)
BEGIN
SELECT @callend = charindex('Terminated', Reason)
from Table1 where ID = @LoopId
set @Call_Count = @Call_Count + case when @callend > 0 then 1 else 0 end
IF @LoopId > 1
begin
update Table1
set Call_Counter = @Call_Count
WHERE Id = @LoopID
end
SET @LoopId = @LoopId + 1
END
我得到的结果是:
ID Date Condition Call_Count
1 2015-03-02 14:05:05 Terminated 1
2 2015-03-02 14:05:05 Terminated 2
3 2015-03-02 14:05:05 Terminated 3
4 2015-03-02 14:05:05 Terminated 4
5 2015-03-02 14:05:10 Transferred 4
6 2015-03-02 14:06:02 Transferred 4
7 2015-03-02 14:07:00 Transferred 4
8 2015-03-02 14:07:50 Terminated 5
9 2015-03-02 14:07:60 Transferred 5
10 2015-03-02 14:08:55 Terminated 6
11 2015-03-02 14:08:56 Terminated 6
我需要生成一个会产生此结果的ID字段,它需要在最后一个“Terminated”之后更改数字,以便将一个“call”放入一个组中。
ID Date Condition Call_Count
1 2015-03-02 14:05:05 Terminated 1
2 2015-03-02 14:05:05 Terminated 2
3 2015-03-02 14:05:05 Terminated 3
4 2015-03-02 14:05:05 Terminated 4
5 2015-03-02 14:05:10 Transferred 5
6 2015-03-02 14:06:02 Transferred 5
7 2015-03-02 14:07:00 Transferred 5
8 2015-03-02 14:07:50 Terminated 5
9 2015-03-02 14:07:60 Transferred 6
10 2015-03-02 14:08:55 Terminated 6
11 2015-03-02 14:08:56 Terminated 7
答案 0 :(得分:3)
应该适用于任何版本的sql server的简单解决方案是使用带有的内部联接到相关派生表的更新
相关的子查询。
创建并填充样本表(请在将来的问题中将此步骤保存起来 - 如果您自己这样做,我会在第一次尝试中发布正确且经过测试的解决方案)
CREATE TABLE Table1
(
ID int identity(1,1),
[Date] datetime,
Condition nvarchar(20),
Call_Counter int
)
INSERT INTO Table1 ([Date], Condition) VALUES
('2015-03-02 14:05:05', 'Terminated'),
('2015-03-02 14:05:10', 'Transferred'),
('2015-03-02 14:06:02', 'Transferred'),
('2015-03-02 14:07:00', 'Transferred'),
('2015-03-02 14:07:50', 'Terminated'),
('2015-03-02 14:07:59', 'Transferred'),
('2015-03-02 14:08:55', 'Terminated'),
('2015-03-02 14:08:56', 'Terminated')
更新声明:
UPDATE t1
SET Call_Counter =
(
SELECT COUNT(*) As CallCounter
FROM Table1 t2
WHERE Condition = 'Terminated'
AND t2.ID <= t1.ID
)
FROM Table1 t1
第一次尝试(错误) <击> 撞击>
<击>UPDATE t1
SET Call_Counter = CallCounter
FROM Table1 t1
INNER JOIN
(
SELECT COUNT(*) As CallCounter
FROM Table1 t2
WHERE Condition = 'Terminated'
AND ID <= t1.ID
) t3
击> <击> 撞击>
答案 1 :(得分:1)
类似的解决方案让Zohar。但我宁愿先计算所有的价值。还可以利用窗口功能。
<强> SQL DEMO 强>
WITH CTE as (
SELECT ID ,
COUNT(CASE WHEN [Condition] = 'Terminated' THEN 1 END)
OVER (ORDER BY [ID]) as rn
FROM Table1
)
UPDATE A
SET [Call_Count] = CASE WHEN [Condition] = 'Terminated'
THEN B.rn
ELSE B.rn + 1
END
FROM Table1 A
JOIN CTE B
ON A.ID = B.ID;