我有一张表,其中包含三个字段:
Id, Creation Time, Fuel Level
每两分钟我们获取数据并插入数据库。为了生成燃料贷记/借记表,我想开始(当天的状态)和结束(当天的结束)燃料水平。任何人都可以帮助形成查询生成此报告?
搜索参数将是日期范围。
id=10;创建时间=2019-02-15 16:32:59;油位=20
我在这里创建了一个示例架构 http://sqlfiddle.com/#!2/76dd5
我有一张表,其中包含三个字段:
Id, Creation Time, Fuel Level
每两分钟我们获取数据并插入数据库。为了生成燃料贷记/借记表,我想开始(当天的状态)和结束(当天的结束)燃料水平。任何人都可以帮助形成查询生成此报告?
搜索参数将是日期范围。
id=10;创建时间=2019-02-15 16:32:59;油位=20
我在这里创建了一个示例架构 http://sqlfiddle.com/#!2/76dd5
首先,对于提供每辆车每天的燃料变化的查询,您可以使用以下 SQL:
SELECT trip_range.dt
, trip_range.vehicle_id
, st.fuel_content as start_fuel_content
, en.fuel_content as end_fuel_content
, en.fuel_content - st.fuel_content as fuel_change
FROM (
SELECT tp.vehicle_id, DATE(tp.creation_time) dt
, MIN(tp.creation_time) start_time
, MAX(tp.creation_time) end_time
FROM trip_parameters tp
GROUP BY tp.vehicle_id, DATE(tp.creation_time)
) as trip_range
JOIN trip_parameters st
ON st.vehicle_id = trip_range.vehicle_id
AND st.creation_time = trip_range.start_time
JOIN trip_parameters en
ON en.vehicle_id = trip_range.vehicle_id
AND en.creation_time = trip_range.end_time
WHERE trip_range.dt BETWEEN '2012-11-08' AND '2012-11-09'
如果您想要该范围内每天所有车辆的燃料累积变化,以下 SQL 应该可以工作:
SELECT dt, SUM(fuel_change) as fuel_change
FROM (
SELECT trip_range.dt
, en.fuel_content - st.fuel_content as fuel_change
FROM (
SELECT tp.vehicle_id, DATE(tp.creation_time) dt
, MIN(tp.creation_time) start_time
, MAX(tp.creation_time) end_time
FROM trip_parameters tp
GROUP BY tp.vehicle_id, DATE(tp.creation_time)
) as trip_range
JOIN trip_parameters st
ON st.vehicle_id = trip_range.vehicle_id
AND st.creation_time = trip_range.start_time
JOIN trip_parameters en
ON en.vehicle_id = trip_range.vehicle_id
AND en.creation_time = trip_range.end_time
WHERE trip_range.dt BETWEEN '2012-11-08' AND '2012-11-09'
) change_by_vehicle
GROUP BY 1
希望这可以帮助!
约翰...
试试下面:
SELECT Id, CreationTime, FuelLevel
FROM MYTABLE
WHERE DATE(CreationTime) = CURDATE();
这将获取日期部分CreationTime
并与当前日期进行比较,从而返回今天创建的所有记录。
这是一个返回输出的查询:
DATE FUEL_CONTENT_AT_START_OF_DAY FUEL_CONTENT_AT_END_OF_DAY
Nov, 08 2012 4.6 3.6
Nov, 09 2012 11.6 5.6
询问
SELECT
DATE( startofday.creation_time) AS date,
startofday.fuel_content AS fuel_content_at_start_of_day,
(SELECT fuel_content FROM trip_parameters WHERE trip_paramid = max(endofday.trip_paramid) ) AS fuel_content_at_end_of_day
FROM
trip_parameters startofday
INNER JOIN trip_parameters endofday ON ( DATE( endofday.creation_time ) = DATE( startofday.creation_time) )
WHERE
DATE( startofday.creation_time) BETWEEN '2012-11-08' AND '2012-11-09'
GROUP BY
startofday.TRIP_PARAMID
HAVING
min( endofday.trip_paramid ) = startofday.trip_paramid
我已经在 SQLFiddle 上更新了相同的内容,http: //sqlfiddle.com/#!2/76dd5/67
查询作为
希望这可以帮助