用于计算行进距离的SQL查询

时间:2013-03-16 06:20:55

标签: c# sql

我有一张类似于车辆和位置的表格

time   |  odo
_______
4:00   |   10

5:00   |   20

6:00   |  30

7:00   |  60

8:00   |  80

我有另一张表,上面列出了时间/气味存在于上表中的车辆清单 所以我需要从vehicleList_table中选择一辆车并在上表中加入一些车辆。

所以,如果我从vehicleList_table和开始时间查询每辆车,我希望得到以下结果:

代表starttime 4:00和endtime 7:00:

___
vehicle  |  startTime  |  endTime  |  distanceTravelled
____
MH01k11   4:00        |     7:00     |      50   (i.e 60-10)
___

这是wt我需要我的数据集,因为我想在gridview中显示上面的输出 是否有可能为上面的内容编写查询,或者我需要依赖c#代码,其中我已经从检索到的记录中进行了手动计算,但要将其复杂加载到gridview中

3 个答案:

答案 0 :(得分:1)

您只需使用一个查询即可:

SELECT
  MIN(time)           AS StartTime,
  MAX(time)           AS EndTime,
  MAX(odo) - MIN(odo) AS distanceTravelled
FROM tablename
WHERE time BETWEEN '4:00' 
               AND '8:00';

SQL Fiddle Demo


更新

对于您在更新问题后要查找的输出:

JOIN这两个表格,并添加WHERE子句,这将为每辆车提供starttimeEndTimedistanceTravelled,并带有{ {1}}:

GROUP BY

Updated SQL Fiddle Demo

这会给你类似的东西:

SELECT
  v.vehicle,
  MIN(l.time) AS StartTime,
  MAX(l.time) AS EndTime,
  MAX(l.odo) - MIN(l.odo) AS travelled
FROM vehiclelist_table AS v
INNER JOIN locations as l ON v.vehicle_id = l.vehicle_id
WHERE l.time BETWEEN '4:00' AND '7:00'
GROUP BY v.vehicle;

如果您只需要为特定车辆执行此操作,请在| VEHICLE | STARTTIME | ENDTIME | TRAVELLED | --------------------------------------------- | MH01k11 | 4:00 | 7:00 | 50 | | MHooooo | 4:00 | 7:00 | 50 | 子句中添加。

我也假设列名和表关系,因为你没有提供它们彼此之间的关系,你可能需要修改列的名称。

答案 1 :(得分:0)

如果你想计算@Starttime和@Endtime之间的距离,你可以这样做:

Select @Starttime startTime,@Endtime Endtime,Max(odo)-Min(odo)
From YourTable
Where time Between @Starttime And @Endtime

答案 2 :(得分:0)

SELECT
  vt.vehiclename as VehicleName
  MIN(ot.time)           AS StartTime,
  MAX(ot.time)           AS EndTime,
  MAX(ot.odo) - MIN(ot.odo) AS distanceTravelled
FROM vehicleTable vt, othertable ot
where vt.vehicleid=ot.vehicleid 
ot.time between time1 and time2
group by vt.vehiclename;