-1

我对 T-SQL 很陌生,我需要一些帮助。我有一个table1. 我怎么能做这个过程?我应该使用嵌套光标还是什么?需要这方面的建议。

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

在此处输入图像描述

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

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'
4

2 回答 2

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

这只是您从上一个事件开始获得时间。我希望这可以为您指出解决方案。如果没有,请更具体地说明您的需要:)

于 2013-04-17T13:21:05.130 回答
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'

我使用你的前三行作为示例数据,这是我在更新后看到的:

在此处输入图像描述

这是你想要的?顺便说一句,我意识到这一切都可以在没有视图的情况下完成,但是,我发现这更容易处理,就逐步解决问题而言。

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

查询以模拟 SQL Server 2008 中的 Lead 函数

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

于 2013-04-17T14:35:09.640 回答