我想更新col并根据批次向列中添加5分钟。
让我们说当前快照:
Time | batch
2015-03-26 08:20:54.077 | 1
2015-03-26 08:20:54.077 | 1
2015-03-26 08:20:54.077 | 1
2015-03-26 08:20:54.077 | 1
2015-03-26 08:20:54.077 | 1
2015-03-26 08:22:54.077 | 2
2015-03-26 08:22:54.077 | 2
2015-03-26 08:22:54.077 | 2
2015-03-26 08:22:54.077 | 2
2015-03-26 08:24:54.077 | 3
2015-03-26 08:24:54.077 | 3
更新后:
My_Time | batch
2015-03-26 08:25:54.077 | 1
2015-03-26 08:25:54.077 | 1
2015-03-26 08:25:54.077 | 1
2015-03-26 08:25:54.077 | 1
2015-03-26 08:25:54.077 | 1
2015-03-26 08:30:54.077 | 2
2015-03-26 08:30:54.077 | 2
2015-03-26 08:30:54.077 | 2
2015-03-26 08:30:54.077 | 2
2015-03-26 08:35:54.077 | 3
2015-03-26 08:35:54.077 | 3
根据我当前的查询,不是achived.Plz指南。
UPDATE table_name SET My_Time = DATEADD(minute, 5, My_Time);
它是根据当前的延迟时间增加时间,但如何在前一批次的基础上更新?
答案 0 :(得分:2)
试试这个
示例数据
DROP TABLE snapshot
CREATE TABLE snapshot (time DATETIME,batchid INT)
INSERT INTO snapshot VALUES('2015-03-26 08:20:54.077', 1),
('2015-03-26 08:20:54.077', 1 ),
('2015-03-26 08:20:54.077', 1),
('2015-03-26 08:20:54.077', 1),
('2015-03-26 08:20:54.077', 1),
('2015-03-26 08:22:54.077', 2),
('2015-03-26 08:22:54.077', 2),
('2015-03-26 08:22:54.077', 2),
('2015-03-26 08:22:54.077', 2),
('2015-03-26 08:26:54.077', 3),
('2015-03-26 08:26:54.077', 3)
SELECT * FROM snapshot;
<强>查询强>
DECLARE @increment_by_mins INT = 5
UPDATE snapshot
SET time = updated_time
FROM snapshot
INNER JOIN
(
SELECT batchid, DATEADD(MINUTE, @increment_by_mins * orderedid,ISNULL(LAG(time) OVER(ORDER BY batchid),time)) updated_time
FROM
(
SELECT MIN(time) time,batchid,ROW_NUMBER()OVER(ORDER BY batchid ASC) as orderedid
FROM snapshot
GROUP BY batchid
)updated_snapshot
)updated_snapshot
ON updated_snapshot.batchid = snapshot.batchid
SELECT * FROM snapshot;
修改强>
根据你的回答,你想要做的似乎与我最初提出的相似。
由于您的所有时间都是基于初始批次的最短时间,因此您只需要DENSE_RANK()
和DATEADD
来完成所需的工作。
DECLARE @initialtime datetime;
SELECT TOP 1 @initialtime = time
FROM snapshot
ORDER BY batchid,time;
DECLARE @minutes INT = 5
;WITH CTE AS
(
SELECT time,batchid,DENSE_RANK()OVER(ORDER BY batchid ASC) oid
FROM snapshot
)
UPDATE CTE
SET time = DATEADD(minute,@minutes * oid ,@initialtime)
SELECT * FROM snapshot
答案 1 :(得分:0)
DECLARE @tempTable TABLE
(
ID int IDENTITY(1,1),
batchid INT
)
INSERT INTO @tempTable
SELECT distinct batchid FROM snapshot
declare @CuentdateTime Datetime =null
set @CuentdateTime =(select top 1 time from snapshot) ;
DECLARE @tempTablecount INT
DECLARE @count INT = 1
SELECT @tempTablecount = COUNT(*) FROM @tempTable
WHILE(@count<=@tempTablecount)
BEGIN
select @CuentdateTime = DATEADD(MINUTE, 5, @CuentdateTime);
UPDATE snapshot SET time = @CuentdateTime where batchid=(select batchid FROM @tempTable where id=@count)
SET @count = @count + 1
END