we have a database table where we store a new record every 30 minutes.
I wrote the following query:
SELECT *
FROM datastore_usage
WHERE datastore_id = 1
GROUP BY HOUR(created_at)
ORDER BY created_at DESC
LIMIT 10;
This query results in the following:
Instead of the first value of the given hour, I would like to get the record with the highest bytes_in_use of this hour.
I have tried to add the MAX(bytes_in_use)
to the query. But then the value is not related to the ID and created at timestamp.
So how can I query the highest record grouped by hour?
Than you in advance.
2
Answers
I finally fixed the issue by using the following query:
This query returns the highest value of each hour. It still returns the first timestamp of the hour. But we will round this timestamp anyway.
Try if it produces desired result and let me know. If yes i can explain.
WITH CTE AS (
SELECT
*,
ROW_NUMBER() OVER (PARTITION BY HOUR(created_at) ORDER BY bytes_in_use DESC) AS row_num
FROM
datastore_usage
WHERE
datastore_id = 1
)
SELECT
*
FROM
CTE
WHERE
row_num = 1
ORDER BY
created_at DESC
LIMIT 10;