计算最快的50公里行驶速度

时间:2019-06-06 16:54:34

标签: sql sql-server

嗨,我从单车心率表中获得了这些速度数据:

declare @DistanceTable Table
(
  Time DateTime2,
  DistanceMeters float
)

insert into @DistanceTable   values 
    ('2018-07-26 07:04:52.0000000',  2.10999989509583),
    ('2018-07-26 07:04:53.0000000',  4.84999990463257),
    ('2018-07-26 07:04:54.0000000',  7.94000005722046),
    ('2018-07-26 07:04:55.0000000', 11.5600004196167),
    ('2018-07-26 07:04:56.0000000', 16.2700004577637),
    ('2018-07-26 07:04:57.0000000', 21.3199996948242),
    ('2018-07-26 07:04:58.0000000', 26.9099998474121),
    ('2018-07-26 07:04:59.0000000', 32.8899993896484),
    ('2018-07-26 07:05:00.0000000', 39),
    ('2018-07-26 07:05:01.0000000', 45.6500015258789),

...

('2018-07-26 08:36:08.0000000', 50003.19921875),
('2018-07-26 08:36:09.0000000', 50010.73046875),
('2018-07-26 08:36:10.0000000', 50018.328125),
('2018-07-26 08:36:11.0000000', 50025.9609375),
('2018-07-26 08:36:12.0000000', 50033.5703125),
('2018-07-26 08:36:13.0000000', 50041.2109375),
('2018-07-26 08:36:14.0000000', 50048.94140625),
('2018-07-26 08:36:15.0000000', 50056.7109375),
('2018-07-26 08:36:16.0000000', 50064.421875),
('2018-07-26 08:36:17.0000000', 50072.1484375)

还有更多数据。

我的问题是:如何计算这条赛道中最快的50公里时间。

范围:Sql Server 2017

2 个答案:

答案 0 :(得分:2)

您可以通过在50公里(在cte中)找到第一行并将结果与​​min()max()分组来实现。然后,我计算了minmax之间的秒差,并将其转换为时间数据类型。我以为每天只有一次乘车,除非你是超人...

  ;with mostCloseTo50 as (
    select
         Time
        ,row_number() over (partition by cast(Time as date) order by DistanceMeters asc) as number
        ,DistanceMeters
    from @DistanceTable
    where DistanceMeters > 50000
)
select 
    cast(dateadd(SECOND,DATEDIFF(SECOND, min(d.Time), max(d.Time)),'00:00:00') as time(0))
from @DistanceTable as d
join mostCloseTo50 as m
    on cast(m.Time as date) = cast(d.Time as date)
    and m.number = 1
    and d.DistanceMeters <= m.DistanceMeters
group by cast(d.Time as date)

结果:

01:31:16

答案 1 :(得分:1)

您可以尝试此脚本。也许更容易理解。结果是所有长度为50 km的路段。在字段“ TimeSegmentSec”中找到分钟。

CREATE CLUSTERED INDEX IX_DistanceTable_DistanceMeters on #DistanceTable (DistanceMeters) 

Declare @Segment int=50000 -- 50 km
Select DT.DistanceMeters as 'Start',DT3.DistanceMeters as 'Finish',DT.Time as 'StartTime',DT3.Time as 'FinishTime'
    ,DATEDIFF(second,DT.Time,DT3.Time) 'TimeSegmentSec',DT3.DistanceMeters-DT.DistanceMeters 'LengthSegment'
from #DistanceTable DT
    cross apply 
    (Select Top 1 Time,DistanceMeters from #DistanceTable DT2 where DT2.DistanceMeters<=DT.DistanceMeters+@Segment order by DistanceMeters desc
    ) as DT3
where DT3.DistanceMeters-DT.DistanceMeters>@Segment-20 -- Exclude shorter segment