更新上一行,从其他行获取值

时间:2013-04-17 10:58:40

标签: sql-server tsql

我对T-SQL很新,我需要一些帮助。我有table1。我怎么做这个过程? 我应该使用嵌套游标还是什么?需要一个建议。

请参考图片 - http://i.stack.imgur.com/CHYIg.gif

enter image description here

到目前为止,这是我的代码:

DECLARE @get_invckey datetime;
SET @get_invckey = '2013-04-09 13:30:43.537'

UPDATE table1
SET RUNTIME = @get_invckey
FROM
    (
    SELECT
        DCREPORTTIME
    FROM table1
    WHERE
        LOCATIONAME = 'MYQ01_PRNT_A_SP3'
        AND EVENT LIKE '%RUN%'
    ) newdata
WHERE
   LOCATIONAME = 'MYQ01_PRNT_A_SP3'
   AND EVENT = 'MACHINE B STOPPED'

2 个答案:

答案 0 :(得分:0)

不完整的答案,因为你的问题不够复杂。

快速而简单的例子如何实现这一目标。

一些示例数据

DECLARE @Table table
(   dcreporttime datetime, event_name varchar(55))


insert INTO @Table
SELECT '2013-04-09 13:34:01', 'RUNNING'
union
SELECT '2013-04-09 13:34:19', 'STOPPED'
union
SELECT '2013-04-09 13:34:29', 'RUNNING'
union
SELECT '2013-04-09 13:34:39', 'RUNNING'
union
SELECT '2013-04-09 13:35:19', 'STOPPED'
union
SELECT '2013-04-09 13:35:29', 'RUNNING'
union
SELECT '2013-04-09 13:35:39', 'RUNNING'
union
SELECT '2013-04-09 13:36:19', 'RUNNING'
union
SELECT '2013-04-09 13:37:19', 'STOPPED'
union
SELECT '2013-04-09 13:37:39', 'RUNNING'

和查询。它使用CTE(公用表表达式)和排名函数:

;with cte as
(
SELECT RANK() OVER(ORDER by dcreporttime) as RankN, *
FROM @Table
)
select a.dcreporttime, a.event_name,  a.dcreporttime, b.dcreporttime, DATEDIFF(ms, a.dcreporttime, b.dcreporttime) as runtime
from cte a 
            -- shift by Rank to compare with previous row
    join cte b on a.RankN = b.RankN + 1

这只是你上次活动以来的时间。我希望这可以指出你的解决方案。如果没有,请更具体地说明您的需求:)

答案 1 :(得分:0)

我已将视图更新如下:

create view [dbo].[cm] as

WITH cteMain
AS
(SELECT DCREPORTTIME, 
ROW_NUMBER() OVER (ORDER BY DCREPORTTIME) AS rn,
RUNTIME,
[EVENT] AS EVENT

FROM
table1),
cte2 as (SELECT 
sLeg.rn,
slead.DCREPORTTIME AS leadvalue,
       sLeg.DCREPORTTIME AS lagvalue,
       m.EVENT

FROM
cteMain AS m
LEFT OUTER JOIN cteMain AS sLead
ON sLead.rn = m.rn+1
LEFT OUTER JOIN cteMain AS sLeg
ON sLeg.rn = m.rn-1) 
SELECT cte2.leadvalue, cte2.lagvalue, cte2.rn, cte2.EVENT
FROM cte2

然后,我将更新查询修改为:

update table1
set RUNTIME = DATEDIFF(ms, lagvalue, leadvalue)
FROM cm 
where leadvalue=table1.DCREPORTTIME
and table1.EVENT='MACHINE RUNNING'

我使用你的前三行作为样本数据,这是我在更新后看到的内容:

enter image description here

这是你在找什么?顺便说一下,我意识到这一切都可以在没有视图的情况下完成,但是,我发现这更容易使用,只要一步一步地解决问题。

我的查询基于我在以下链接中找到的查询:

Query to simulate Lead function in SQL Server 2008

请参阅SQLFiddle:SQLFiddle for Update previous row, get value from other row