组中的时差

时间:2013-01-11 10:46:22

标签: sql-server-2008 tsql

我的表格如下:

    GroupOrderID    Station           Date
-----------------------------------------------
    28797   NB003   2013-01-03 12:53:00
    28797   NB003   2013-01-03 17:12:00
    28797   NB003   2013-01-04 14:45:00
    28797   NB003   2013-01-04 15:57:00
    28797   NB003   2013-01-06 16:08:00
    28797   NB003   2013-01-07 10:28:00
    28797   NB003   2013-01-07 10:29:00
    28797   CRM220  2013-01-07 16:31:00
    28797   CRM220  2013-01-07 17:04:00
    28797   CRM220  2013-01-07 17:04:00
    28797   CRM220  2013-01-07 17:04:00
    28797   CRM220  2013-01-07 17:04:00
    28797   CRM220  2013-01-07 17:24:00
    28797   CRM220  2013-01-07 17:24:00
    28797   STEENOVE    2013-01-11 11:03:00

我希望两个日期之间的时差以秒为单位。对于每个站点,就像Station NB003,CRM220每个都有第一个和最后一个日期,我希望在几秒钟内有所不同。

2 个答案:

答案 0 :(得分:2)

通过应用max()min()聚合函数,然后使用DateDiff(),您应该能够获得结果。

select GroupOrderID, 
  station,
  datediff(ss, MinDate, MaxDate) DiffSeconds
from
(
  select GroupOrderID, 
    station, 
    min(date) MinDate,
    Max(Date) MaxDate
  from yourtable
  group by GroupOrderID, Station
) src

请参阅SQL Fiddle with Demo

结果是:

| GROUPORDERID |  STATION | DIFFSECONDS |
-----------------------------------------
|        28797 |   CRM220 |        3180 |
|        28797 |    NB003 |      336960 |
|        28797 | STEENOVE |           0 |

如果您想知道每个日期的差异,可以再采取此步骤:

select GroupOrderID, 
  station,
  Date,
  datediff(ss, MinDate, MaxDate) DiffSeconds
from
(
  select GroupOrderID, 
    station,
    Cast(date as date) date,
    min(date) MinDate,
    Max(Date) MaxDate
  from yourtable
  group by GroupOrderID, Station, Cast(date as date)
) src
order by date

请参阅SQL Fiddle with Demo

结果是:

| GROUPORDERID |  STATION |       DATE | DIFFSECONDS |
------------------------------------------------------
|        28797 |    NB003 | 2013-01-03 |       15540 |
|        28797 |    NB003 | 2013-01-04 |        4320 |
|        28797 |    NB003 | 2013-01-06 |           0 |
|        28797 |   CRM220 | 2013-01-07 |        3180 |
|        28797 |    NB003 | 2013-01-07 |          60 |
|        28797 | STEENOVE | 2013-01-11 |           0 |

答案 1 :(得分:0)

;with CTE(GroupOrderId, station, Date , r_asc, r_desc) as 
(
select GroupOrderId, station, Date , row_number() over(partition by GroupOrderId, station order by date ) as r_asc, row_number() over(partition by GroupOrderId, station order by date desc) as r_desc
from #temp
)
select a.GroupOrderId, a.station, datediff(SECOND, a.date, b.date)
from CTE a join CTE b on a.GroupOrderId = b.GroupOrderId and a.station = b.station and a.r_asc =1 and b.r_desc = 1