1. 程式人生 > >MySQL查詢某個時間段內所有的記錄總數

MySQL查詢某個時間段內所有的記錄總數

因為需要完成如下圖的效果需要查詢出最近一個時間段內所有的記錄總數


有兩種方法HOUR()和DATE_FORMAT()。

HOUR()使用時如果計算最近一天的記錄需要新增過濾條件,而DATE_FORMAT()不需要新增過濾條件預設查詢最近一天的記錄

例子:

SELECT
	thermometer_return as '是否冷鏈',
	COUNT(id) as '數量',
	HOUR (create_date) as '時間'
FROM
	order_sale
WHERE
	company_id = '2'
AND del_flag = '0'
AND create_date >= '2017-07-25 00:00:00.0'
AND create_date <= '2017-07-25 12:00:00.0'
GROUP BY
	HOUR (create_date),
	thermometer_return
ORDER BY
	create_date


SELECT DATE_FORMAT(create_date, '%H') as '時間', COUNT(*) as '記錄總數',thermometer_return as '是否冷鏈' FROM order_sale
WHERE
	company_id = '2'
AND del_flag = '0'
-- AND create_date >= '2017-07-25 00:00:00.0'
-- AND create_date <= '2017-07-25 12:00:00.0'
GROUP BY DATE_FORMAT(create_date, '%H'),thermometer_return;