SUM和UPDATE #temp跳过记录

时间:2014-04-02 22:28:10

标签: sql sql-server-2012

我有这个数据的临时表#tbl这个顺序,我试图计算第一个记录与第二个记录之间的差异,第二个记录与第三个记录之间的差异,依此类推,更新结果名为Diff的字段

要解决的第二个问题是我必须从CodeId 22到23只取差异,我必须丢弃CodeId从23到下一个22之间的差异.I CodeId = 22是GO,23 =停止,我必须计算驾驶时间。

  Fecha               Driver   CodeId  Diff
  2014/03/01 14:00:00, 7168,     22  ,  0
  2014/03/01 14:30:00, 7168,     23  ,  0
  2014/03/01 14:40:00, 7168,     22  ,  0
  2014/03/01 16:10:00, 7168,     23  ,  0
  2014/03/01 16:50:00, 7168,     22  ,  0
  2014/03/01 17:20:00, 7168,     23  ,  0
  2014/03/01 18:30:00, 7168,     22  ,  0
  2014/03/01 19:10:00, 7168,     23  ,  0

我写了这段代码,但我得到了错误:

    UPDATE #tbl
    SET Difer = DATEDIFF(second, Fecha, LEAD(Fecha,1, Fecha) OVER (ORDER BY Fecha))
    FROM #tbl

    Msg 4108, Level 15, State 1, Line 2
    Windowed functions can only appear in the SELECT or ORDER BY clauses.

我正在使用MS SQL Server 2012

不知道如何解决,请你帮我。谢谢。

PD:我在等待帮助时写了这段代码

    ; WITH Sumar AS (
     Select Fecha as Fecha1, 
         DATEDIFF(second, Fecha, LEAD(Fecha,1, Fecha) OVER (ORDER BY Fecha)) as Total
     FROM #tbl)
    UPDATE #tbl
    SET Difer = Total
    FROM Sumar
    WHERE Fecha = Fecha1 AND EvenTypeId <> 23

对我来说很好。谢谢大家。

1 个答案:

答案 0 :(得分:1)

试试这个

;WITH CTE_GO
AS(  
 SELECT Fecha , Driver, CodeId,Diff,
        ROW_NUMBER() OVER (ORDER BY Fecha ASC) RN_Go
 FROM  #tbl
 WHERE CodeId = 22
 ),
 CTE_Stop
 AS
 (
 SELECT Fecha , Driver, CodeId,Diff,
        ROW_NUMBER() OVER (ORDER BY Fecha ASC) RN_Go
 FROM  #tbl
 WHERE CodeId = 23
 )
UPDATE  S
SET S.Diff = DATEDIFF(MINUTE, G.Fecha, S.Fecha) 
FROM CTE_GO G INNER JOIN CTE_Stop S
ON G.RN_Go = S.RN_Go

结果集

╔═════════════════════════╦════════╦════════╦══════╗
║          Fecha          ║ Driver ║ CodeId ║ Diff ║
╠═════════════════════════╬════════╬════════╬══════╣
║ 2014-03-01 14:00:00.000 ║   7168 ║     22 ║    0 ║
║ 2014-03-01 14:30:00.000 ║   7168 ║     23 ║   30 ║
║ 2014-03-01 14:40:00.000 ║   7168 ║     22 ║    0 ║
║ 2014-03-01 16:10:00.000 ║   7168 ║     23 ║   90 ║
║ 2014-03-01 16:50:00.000 ║   7168 ║     22 ║    0 ║
║ 2014-03-01 17:20:00.000 ║   7168 ║     23 ║   30 ║
║ 2014-03-01 18:30:00.000 ║   7168 ║     22 ║    0 ║
║ 2014-03-01 19:10:00.000 ║   7168 ║     23 ║   40 ║
╚═════════════════════════╩════════╩════════╩══════╝