Fetch hourly data from MySQL

人盡茶涼 提交于 2021-02-11 12:31:44

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!