sql-- query data per hour of day

First, build a tool table has only one field 0-23 hour

CREATE TABLE `date_tool` (
  `hour` int(3) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;

Insert 0-23 Digital

Second, the association left the main table 0-23, Null is set to 0 ifnull (field 0)

Attached sql

SELECT
dt. HOUR,
ifNULL(s.number, 0) AS number
FROM
date_tool dt
LEFT JOIN (
SELECT
HOUR (r.capture_time) AS HOUR,
count(*) AS number
FROM
md_capture_record r
WHERE
DATE_FORMAT(r.capture_time, '%y-%M-%d') = DATE_FORMAT(NOW(), '%y-%M-%d')
GROUP BY
HOUR
) s ON dt.`hour` = s. HOUR
ORDER BY
dt.`hour`

 

Guess you like

Origin www.cnblogs.com/chaoswu/p/11460231.html