2

I was trying to find the answer to the above here and in other forums.

Given a table valuetable

  • ID : somevalues : date_time
  • 1 : 50 : 2012-10-05 13:00:00
  • 2 : 45 : 2012-10-05 13:15:00
  • 3 : 35 : 2012-10-05 13:20:00
  • 4 : 20 : 2012-10-05 15:00:00
  • 5 : 45 : 2012-10-05 15:25:00
  • 6 : 35 : 2012-10-05 15:35:00

and so on, how do you find the minimum and maximum values along with the corresponding date and time grouped by hour, day, month etc.

The problem here is that GROUP in SQL groups only the hour and IN MYSQL, would return the first date time that occurs in the set or table. I understand that the implementation is different in other RDBMS. Therefore, I used ORDER BY to first order the table so that when we ran the query, the values are ordered in ascending and descending corresponding to Minimum and Maximum query such that when we pick the min and max values per hour, the first date-time that the query picks is the one related to the minimum or maximum values.

The query to pull both minimum and maximum per the hour is given below,

SELECT 
        * 
FROM(
    SELECT 
        HOUR(DATE_TIME) AS MINHOUR, 
        MIN(SOMEVALUES) AS  MINVALUES, 
        DATE_TIME AS MINDATETIME FROM (SELECT * FROM VALUETABLE
    WHERE DATE_TIME>'2012-10-05 00:00:00' 
    AND DATE_TIME<'2012-10-05 23:59:59' 
    ORDER BY SOMEVALUES
    ) AS TEMPT1 
    GROUP BY HOUR(DATE_TIME)
    ) AS    MINVALTABLE 
LEFT JOIN (
    SELECT 
        HOUR(DATE_TIME) AS MAXHOUR,
        MAX(SOMEVALUES) AS MAXVALUES, 
        DATE_TIME AS MAXDATETIME FROM 
        (
            SELECT 
                *
            FROM VALUETABLE 
            WHERE DATE_TIME>'2012-10-05 00:00:00' 
            AND DATE_TIME<'2012-10-05 23:59:59' 
            ORDER BY SOMEVALUES DESC
        ) AS TEMPT2
GROUP BY HOUR(DATE_TIME)) AS MAXVALTABLE 
ON  MINVALTABLE.MINHOUR=MAXVALTABLE.MAXHOUR;

The query should output as here,

  • MINHOUR | MINVALUES | MINDATETIME | MAXHOUR | MAXVALUES | MAXDATETIME
  • 13 | 35 | 2012-10-05 13:20:00 | 13 | 50 | 2012-10-05 13:00:00
  • 15 | 20 | 2012-10-05 15:00:00 | 15 | 45 | 2012-10-05 15:25:00

Kindly, let me know if I missed anything or if there is a better way of doing this.

As I understand it, the query can similarly be used to group by day, month etc.

1 Answer 1

0

Try this query for maximum

SELECT
    t.id,
    DATE_FORMAT(lt.datetime, '%H') as Hour,
    DATE_FORMAT(lt.datetime, '%d') as Day,
    DATE_FORMAT(lt.datetime, '%m') as Month
FROM table as t
LEFT JOIN (SELECT MAX(id),datetime FROM table)  as lt ON lt.id = t.id
GROUP BY Month , Day , Hour

And if it is not what you want please clearify your question

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.