如何在MS SQL Server中减去两个连续的行?

时间:2015-04-27 12:04:52

标签: sql sql-server sql-server-2012

表格如下:

id    | location | datetime
------| ---------| --------
CD123 | loc001   | 2010-10-21 13:30:15
ZY123 | loc001   | 2010-10-21 13:40:15
YU333 | loc001   | 2010-10-21 13:41:00
AB456 | loc002   | 2011-1-21 14:30:30
FG121 | loc002   | 2011-1-21 14:31:00
BN010 | loc002   | 2011-1-21 14:32:00

假设表已按升序日期时间排序。我试图找到位置中连续两行之间的时间(以秒为单位)。

结果表应该是:

| location | elapse 
| loc001   | 600  
| loc001   | 45
| loc002   | 30
| loc002   | 60

由于id是随机生成的,因此很难在查询中编写类似a.id = b.id + 1的内容。并且只会连续减去同一位置内的行,而不是跨越不同的位置。

我应该如何在MS SQL Server中编写查询来完成它?

5 个答案:

答案 0 :(得分:4)

在SQL Server 2012及更高版本中,您可以使用LEADLAG

SELECT 
   location,
   SUM(DATEDIFF(SECOND, DateTime, 
                Lead(DateTime, 1) OVER(PARTITION BY location ORDER BY DateTime))) Elepase 
FROM 
    tableName  
GROUP BY 
    location

答案 1 :(得分:2)

with Result as 
(Select *, ROW_NUMBER() Over (order by location,datetime) RowID from table_name  )
Select R1.location,DATEDIFF(SECOND,R2.datetime,R1.datetime)   from Result R1     Inner join Result R2 on (R1.RowID=R2.RowID+1 and R1.location=r2.location)

答案 2 :(得分:0)

您有两种选择:

添加新的Row number column,然后在ID上自行加入,例如[新ID] = [新ID] - 1.然后您可以进行减法,即表1。[新ID] - 表2. [新ID]

使用LAG function这是上述方法的快捷方式。只要您使用SQL2012 +

答案 3 :(得分:0)

创建cte并使用lead将datetime和next_datetime放在同一行。 然后使用此cte

datediff计算
WITH cte
    AS
    (
        SELECT location
        ,      datetime
        ,      lead(datetime,1) OVER (patition BY location ORDER BY datetime asc) next_datetime
        from tbl)
    SELECT location
    ,      datediff(ss,next_datetime,datetime) Elepase 
    FROM cte

答案 4 :(得分:0)

您可以尝试这种方式:

  select s.location,
         s.datetime,
         datediff(ss, s.datetime, s.prev_datetime)
    from (
           select location, 
                  datetime,
                  lead(datetime) over (partition by location order by datetime ) prev_datetime
             from Table1 
         ) s
   where s.prev_datetime is not null
order by s.location, 
         s.datetime desc