1. 程式人生 > >mysql 時間範圍內分時段分組排序

mysql 時間範圍內分時段分組排序

SELECT 
		nums,
		count(*) TimesParSum,
		sum(CHARGE_TOTAL) TimesParSum
FROM (
	SELECT
		CASE
				WHEN REALSTARTTIME >= '20170623000000'
				AND REALENDTIME < '20170623040000' THEN
					1
				WHEN REALSTARTTIME >= '20170623040000'
				AND REALENDTIME < '20170623080000' THEN
					2
				WHEN REALSTARTTIME >= '20170623080000'
				AND REALENDTIME < '20170623120000' THEN
					3
				WHEN REALSTARTTIME >= '20170623120000'
				AND REALENDTIME < '20170623160000' THEN
					4
				WHEN REALSTARTTIME >= '20170623160000'
				AND REALENDTIME < '20170623200000' THEN
					5
				WHEN REALSTARTTIME >= '20170623200000'
				AND REALENDTIME < '201706231235959' THEN
					6
		END as nums
	FROM
		order_info
	WHERE
		CREATED_USER = '0E566186A56FB870'
	AND REALSTARTTIME >= '20170623000000'
	AND REALENDTIME <=   '201706231235959'

) t GROUP BY nums order by nums ASC

最近在專案中遇到一個需要對錶中的資料,按照一個給定的時間間隔分組並統計個數,需求如圖:


解決方案:

如上程式碼

ps:如果時間區域跨越兩個時間段,eg:start 02:00~ end 06:00,這種根據相應的需求進行解決,1:可以取單獨一個startTime or endTime進行sql作對比