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

最近在项目中遇到一个需要对表中的数据,按照一个给定的时间间隔分组并统计个数,需求如图:

mysql 时间范围内分时段分组排序_第1张图片

解决方案:

如上代码

ps:如果时间区域跨越两个时间段,eg:start 02:00~ end 06:00,这种根据相应的需求进行解决,1:可以取单独一个startTime or endTime进行sql作对比

mysql 时间范围内分时段分组排序_第2张图片

你可能感兴趣的:(mybits)