0

我有如下表格:

    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 一样,每个日期都有第一个和最后一个日期,我想要以秒为单位的差异。

4

2 回答 2

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

结果是:

| 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

结果是:

| 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 |
于 2013-01-11T10:51:03.667 回答
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 
于 2013-01-11T10:59:52.477 回答