我有一张包含gps数据的表格
它每30秒保存一次记录
记录包含speed
(浮点数),CurrTime
(日期时间)和CarID
(int)
如何(每辆车和每天)获得这些值:
停止表示其
speed must be <5 for continous 15 minutes
car1 on 7/7/2017
- 停了10个小时
- 开车14个小时
CREATE TABLE [dbo].[T_Tracking](
[id] [int] ,
[IMEI] [nvarchar](50) NULL,
[TrackTime] [datetime] NULL,
[CurrTime] [datetime] NULL CONSTRAINT [DF_T_Tracking_CurrTime] DEFAULT (getutcdate()),
[Longitude] [nvarchar](50) NULL,
[Lattitude] [nvarchar](50) NULL,
[speed] [float] NULL,
[SafeAreaID] [int] NULL,
[GeoFenceID] [int] NULL,
[CarID] [int] NULL,
[Country] [nvarchar](50) NULL,
[City] [nvarchar](50) NULL,
[Area] [nvarchar](50) NULL,
[Street] [nvarchar](50) NULL,
[FullAddress] [nvarchar](150) NULL,
[Distance] [float] NULL )
此SQLFiddle会自动填充表定义和一些数据示例
(停车场) 忽略交通阻塞
CarName Date DrivePeriod StopPeriod
Car1 7/7/2017 16 8
Car2 7/7/2017 14 10
car3 7/7/2017 12 12
car1 6/7/2017 15 9
SELECT carid
,sum( LAG( TrackTime, 1, Null) OVER (PARTITION BY carid ORDER BY carid)- TrackTime)
FROM T_Tracking
group by carid
Msg 8120,Level 16,State 1,Line 2
专栏&#39; T_Tracking.TrackTime&#39;是 在选择列表中无效,因为它不包含在任何一个中 聚合函数或GROUP BY子句。
Msg 4109,Level 15,State 1,Line 2
窗口函数不能在另一个函数的上下文中使用 窗口函数或聚合。
尝试2
SELECT
carid
, TrackTime
, LAG( TrackTime, 1, Null) OVER (PARTITION BY carid ORDER BY carid) as trackold
, CONVERT(date, TrackTime) as TrackDay
, speed,DATEDIFF(minute, LAG( TrackTime, 1, Null) OVER (PARTITION BY carid ORDER BY carid),TrackTime)
FROM T_Tracking
这个问题在这里,当滞后记录在另一天它得到错误的subtarction
我需要在同一天提出一项指令
答案 0 :(得分:0)
构建一个CTE,计算每列是否被视为已停止
+ GROUP BY YEAR(CurrTime), MONTH(CurrTime), DAY(CurrTime), CarId, Stopped
将完成这项工作。
然后你只需要SUM()
当前记录时间之间的时间量
及其LAG()
值已完成。
WITH CTE "Common Table Expression"(从SQL Server 2008开始)
GROUP BY(从SQL Server 2008开始)
SUM Function(从SQL Server 2008开始)
LAG Function(从SQL Server 2012开始)
很容易说,如果你在SQL Server 2008下,这将是非常棘手的。
如果您在SQL Server 2012下,则可以使用子选项替换LAG函数。
WITH Stopped
AS
( CTE_query_definition )
SELECT
YEAR(CurrTime)
,MONTH(CurrTime)
,DAY(CurrTime)
,CarID
,Stopped
,SUM(CurrTime - LAG(CurrTime) OVER ( order_by_clause ))
FROM [dbo].[T_Tracking]
GROUP BY YEAR(CurrTime),MONTH(CurrTime),DAY(CurrTime),CarID,Stopped
然后您只需要替换( CTE_query_definition)
和order_by_clause
来实现目标