[英]Compare two rows in SQL Server and return only one row
I have a table (trips) that has response data with columns:我有一个表(行程),其中包含带有列的响应数据:
Often two vehicles will respond to the same address on the same date, and I need to find the one that was there first.通常两辆车会在同一天回复同一个地址,我需要找到最先到达的那一辆。
I've tried this:我试过这个:
SELECT
TripDate,
Job,
Vehicle,
DispatchDateTime
(SELECT min(OnSceneDateTime)
FROM Trips AS FirstOnScene
WHERE AllTrips.TripDate = FirstOnScene.TripDate
AND AllTrips.Address = FirstOnScene.Address) AS FirstOnScene
FROM
Trips AS AllTrips
But I still get both records returned, and both have the same FirstOnScene time
.但是我仍然返回了两条记录,并且两者都有相同的
FirstOnScene time
。
How do I only get THE record, with it's DispatchDateTime
and OnSceneDateTime
, and not the row of the trip that was on scene second?我如何只获得记录,它是
DispatchDateTime
和OnSceneDateTime
,而不是第二个场景中的旅行行?
Here are a few example rows from the table:以下是表中的一些示例行:
2016-01-01 0169-a 150 Main St 2016-01-01 16:52 2016-01-01 16:59 Truck 1
2016-01-01 0171-a 150 Main St 2016-01-01 16:53 2016-01-01 17:05 Truck 2
2016-01-01 0190-a 29 Spring St 2016-01-01 17:19 2016-01-01 17:30 Truck 5
2016-01-02 0111-a 8 Fist St 2016-01-02 09:30 2016-01-02 09:40 Truck 1
2016-01-02 0112-a 8 Fist St 2016-01-02 09:32 2016-01-02 09:38 Truck 2
In the above examples I need to return the first, third, and last row of that data set.在上面的示例中,我需要返回该数据集的第一行、第三行和最后一行。
Here is a total shot in the dark based on the sparse information provided.这是基于提供的稀疏信息在黑暗中进行的总拍摄。 I don't really know what defines a given incident so you can adjust the partition accordingly.
我真的不知道是什么定义了给定的事件,因此您可以相应地调整分区。
with sortedValues as
(
select TripDate
, Job
, Vehicle
, OnSceneDateTime
, ROW_NUMBER() over(partition by Address, DispatchDateTime order by OnSceneDateTime desc) as RowNum
from Trips
)
select TripDate
, Job
, Vehicle
, OnSceneDateTime
from sortedValues
where RowNum = 1
You can just filter the rows down by selecting only the MIN
OnSceneDateTime like below:您可以通过仅选择
MIN
OnSceneDateTime 来过滤行,如下所示:
SELECT TripDate, Job, Vehicle, DispatchDateTime,OnSceneDateTime FirstOnScene
FROM Trips as AllTrips
WHERE AllTrips.OnSceneDateTime = (SELECT MIN(OnSceneDateTime)
FROM Trips as FirstOnScene
WHERE AllTrips.TripDate = FirstOnScene.TripDate
and AllTrips.Address = FirstOnScene.Address
)
如何在 OnSceneDateTime 上使用 ORDER BY 然后限制 1. 像这样的简化版本:
SELECT TripDate, Job, Vehicle, DispatchDateTime, OnSceneDateTime FROM trips ORDER BY OnSceneDateTime LIMIT 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.