简体   繁体   English

T-SQL在最后一分钟对至少具有一个位置的IsGood等于true的所有车辆进行计数

[英]T-SQL Count all Vehicles that have at least one position with IsGood equal to true in the last minute

I have a table called VehiclePosition that contains a big amount of data that is increasing aprox every second. 我有一个名为VehiclePosition的表,其中包含大量数据,这些数据每秒都在增加aprox。

The structure of this table is something like: 该表的结构类似于:

VId       | TimestampLocal                     | IsGood
----------+------------------------------------+--------
20        | 2017-08-25 13:17:13.6000000 -04:00 | 1
20        | 2017-08-25 13:17:14.2000000 -04:00 | 1
20        | 2017-08-25 13:17:19.8000000 -04:00 | 0
21        | 2017-08-25 13:17:58.6000000 -04:00 | 0
21        | 2017-08-25 13:18:00.1000000 -04:00 | 0

The query should return just VehicleId 20 because in the last minute (13:17 - 13.18) only this vehicle had at least one position with IsGood = 1. 该查询应仅返回VehicleId 20,因为在最后一刻(13:17-13.18)只有该车辆具有IsGood = 1的至少一个位置。

My query 我的查询

select p.VId 
from VehiclePosition p 
where p.VId = (select distinct VId 
               from VehiclePosition 
               where TimestampLocal > GETDATE() 
                     and IsGood = 0)

but it seems that loads very slow and returns 但加载速度似乎很慢,并且会返回

Subquery returned more than 1 value. 子查询返回的值超过1。 This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression. 当子查询遵循=,!=,<,<=,>,> =或将子查询用作表达式时,不允许这样做。 and I don't know what am I doing wrong. 而且我不知道我在做什么错。

I'm new in T-SQL queries, so please be gentle :) 我是T-SQL查询的新手,所以请保持谨慎:)

The marker for a vehicle which should appear in your result is that within one minute of the greatest timestamp value in your table that vehicle appeared at least once in good condition. 结果中应该出现的车辆标记是,在表格中最大时间戳值的一分钟内,该车辆至少出现过一次状况良好。 If so, you can try the following query: 如果是这样,您可以尝试以下查询:

SELECT DISTINCT
    p.VId
FROM VehiclePosition p
WHERE
    IsGood = 1 AND
    TimestampLocal >= DATEADD(minute, -1, GETDATE())

I used SELECT DISTINCT here because we only want to report each vehicle once. 我在这里使用SELECT DISTINCT是因为我们只想报告每辆车一次。 That is, if a vehicle appeared in the last minute in good condition twice, we would only want to list it once. 也就是说,如果车辆在最后一刻状况良好两次出现,那么我们只想列出一次。

select * from VehiclePosition P 
    where abs(datediff(minute, P.timestamp_local, getdate())) <= 1 and is_good = 1

Result (with the current date = '2017-08-25 13:18' ): 结果(当前日期= '2017-08-25 13:18' ):

id  timestamp_local         is_good
--- ----------------------- -------
20  2017-08-25 13:17:13.000 1
20  2017-08-25 13:17:14.000 1

Rextester Demo. Rextester演示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM