- MySQL获取当天24小时的各个时间段
SELECT
a.hours,
ifnull( count, 0 ) AS value
FROM (
SELECT DATE_FORMAT( DATE_SUB( DATE_FORMAT( NOW(),'%Y-%m-%d'),INTERVAL ( -(@i:=@i+1) ) HOUR ) ,'%Y%m%d%H') AS hours
FROM (
SELECT a FROM
(SELECT '1' AS a UNION SELECT '2' UNION SELECT '3' UNION SELECT '4' ) AS a
JOIN ( SELECT '1' UNION SELECT '2' UNION SELECT '3' UNION SELECT '4' UNION SELECT '5' UNION SELECT '6' ) AS b
ON 1
) AS b , (SELECT @i:=-1) AS i
) a
LEFT JOIN (
SELECT DATE_FORMAT( trans_time, '%Y%m%d%H' ) hours , count( 0 ) AS count
FROM
tms_order
WHERE del_flag = 0 and order_status = 5
GROUP BY hours
) as b ON a.hours = b.hours
ORDER BY hours asc
参考:https://blog.csdn.net/zuochunping/article/details/102499637
- 统计最近7天的数据
SELECT
date(a.trans_time) as date,
ifnull( count, 0 ) AS value
FROM
(
SELECT
date_sub( now(), INTERVAL 1 DAY ) AS trans_time UNION ALL
SELECT
date_sub( now(), INTERVAL 2 DAY ) AS trans_time UNION ALL
SELECT
date_sub( now(), INTERVAL 3 DAY ) AS trans_time UNION ALL
SELECT
date_sub( now(), INTERVAL 4 DAY ) AS trans_time UNION ALL
SELECT
date_sub( now(), INTERVAL 5 DAY ) AS trans_time UNION ALL
SELECT
date_sub( now(), INTERVAL 6 DAY ) AS trans_time UNION ALL
SELECT
date_sub( now(), INTERVAL 7 DAY ) AS trans_time
) as a
LEFT JOIN ( SELECT date(trans_time) AS trans_time, count( 0 ) AS count
FROM
tms_order
WHERE del_flag = 0 and order_status = 5
GROUP BY
date(trans_time)
) as b ON date(a.trans_time) = date(b.trans_time)
ORDER BY date asc