MySQL: Get start & end timestamp for each day

2019-03-05 13:18发布

问题:

Similar to the question at MYSQL: Find Start and End Timestamp of a consecutive count, I have a table with similar data:

StatusTime          | Reading   
2014-01-01 00:00    | 255
2014-01-01 01:00    | 255
2014-01-01 02:00    | 255
2014-01-01 03:00    | 255
2014-01-01 04:00    | 255
2014-01-01 05:00    | 241
2014-01-01 06:00    | 189
2014-01-01 07:00    | 100
2014-01-01 08:00    | 20
2014-01-01 09:00    | 0
2014-01-01 10:00    | 1
2014-01-01 11:00    | 1
2014-01-01 12:00    | 0
2014-01-01 13:00    | 21
2014-01-01 14:00    | 1
2014-01-01 15:00    | 0
2014-01-01 16:00    | 12
2014-01-01 17:00    | 63
2014-01-01 18:00    | 102
2014-01-01 19:00    | 198
2014-01-01 20:00    | 255
2014-01-01 21:00    | 255
2014-01-01 22:00    | 255
2014-01-01 23:00    | 255
2014-01-02 00:00    | 255
2014-01-02 01:00    | 255
2014-01-02 02:00    | 255
2014-01-02 03:00    | 255
2014-01-02 04:00    | 255
2014-01-02 05:00    | 208
2014-01-02 06:00    | 100
2014-01-02 07:00    | 48
2014-01-02 08:00    | 0
2014-01-02 09:00    | 0

I'd like to extract the start and end timestamps where readings go above 50 and below 50, respectively. I just can't get my head around the SQL presented in the other answer!

Thanks in advance for your help.

回答1:

If it only goes below/above again once per day, you can make the query quite simple; just find the min and max time where it's below, grouping by date.

SELECT
  DATE(statustime) statusdate,
  MIN(CASE WHEN reading<50 THEN statustime ELSE NULL END) start_time,
  MAX(CASE WHEN reading<50 THEN statustime ELSE NULL END) end_time
FROM myTable
GROUP BY statusdate

An SQLfiddle to test with.



回答2:

Try this code:

  select *
    (select max(StatusTime) from tbl where Reading > 50) above_50,
    (select min(StatusTime) from tbl where Reading < 50) bellow_50;


回答3:

Something like this?

SELECT DISTINCT MAX(StatusTime), MIN(StatusTime) 
FROM table_name
WHERE Reading < 50 OR Reading > 50;