用于生成报告的MySql查询

时间:2012-11-06 04:25:58

标签: mysql sql

我有一个表有三个字段:

Id, Creation Time, Fuel Level

每两分钟我们就会获取数据并插入数据库。为了生成燃料信用/借记声明,我想开始(说明当天)和结束(一天结束)燃料等级。任何人都可以帮忙形成用于生成此报告的查询?

搜索参数将是日期范围。

Id = 10;创建时间= 2019-02-15 16:32:59;燃料水平= 20

我在这里创建了一个示例模式 http://sqlfiddle.com/#!2/76dd5

3 个答案:

答案 0 :(得分:3)

首先,对于每天为每辆车提供燃料变化的查询,您可以使用以下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

希望这有帮助!

...约翰

答案 1 :(得分:1)

尝试以下:

   SELECT Id, CreationTime, FuelLevel
   FROM MYTABLE
   WHERE DATE(CreationTime) = CURDATE();

这将获取CreationTime的日期部分并与当前日期进行比较,从而返回今天创建的所有记录。

答案 2 :(得分:1)

这是一个返回输出的查询:

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

上更新了相同的内容

查询作为

  • 排好队
    • 在同一天获取所有相应的行
    • 在同一天获取最低和最高身份证件
  • 如果当前行Id等于来自JOIN的最小Id,则显示它,否则忽略
    • 使用子查询中的最大ID来获取结束日期的燃料<_litent

希望这有帮助