问题
The query below retrieves Date Hourly and groups the data into hourly format
SELECT Hour(created) AS hour, created,image
FROM user_screenshot
WHERE created BETWEEN ( Curdate() + INTERVAL (SELECT Hour(Now())) hour -
INTERVAL 23 hour ) AND Now() AND date(created) = '2021-01-27'
GROUP BY hour
ORDER BY ( Curdate() + INTERVAL (SELECT Hour(Now())) hour - INTERVAL 23 hour )
It prints the data this way
which is okay. But Is it possible to retrieve all the records as well which belongs to that hour. For the example above query says there are 447 records in hour 21 and 1 result in 22 hour. Is it possible in one query to fetch those results as well which exist in the database against those hours.
Expecting Output this way
回答1:
You can do this Using INNER JOIN on the same table.
SELECT a.hour, a.Count, b.* FROM user_screenshot as b
INNER JOIN (
SELECT Hour(created) AS hour, created, COUNT(*) AS Count
FROM user_screenshot
WHERE created BETWEEN ( Curdate() + INTERVAL (SELECT Hour(Now())) hour - INTERVAL 23 hour ) AND Now()
GROUP BY hour
ORDER BY ( Curdate() + INTERVAL (SELECT Hour(Now())) hour - INTERVAL 23 hour )
) as a
ON Hour(a.created) = Hour(b.created) WHERE date(b.created) = '2021-01-27'
回答2:
Yes you can use Group_concat() function to get all those values as an single array.
Example.
Group_concat(column_name) as alias_name,
this will get all the values in a single row
来源:https://stackoverflow.com/questions/65933673/fetch-hourly-data-from-mysql