需要在MySQL的第二天下午5点到次日凌晨5点找到总数(总和)

时间:2018-03-03 19:21:01

标签: mysql

我有一张MySQL数据表,其中包含出租车/超级游乐设施的收入,其中包含以下字段:

id
ride_date 
ride_earnings
ride_tips

我正在努力获得最多"盈利的列表"约会,我能做到:

SELECT DATE(ride_date) as d, SUM(ride_earnings+ride_tips) as total, COUNT(id) as ride_count 
FROM rides 
GROUP by d 
ORDER BY total DESC

但我需要将它们分组为所有游乐设施,从一天的中午12点开始 - 第二天中午12点。提前致谢!

编辑:从12p - 12p改为使其更简单

EDIT2:另外,我应该说明这一点,但我将通过PHP提取这些数据,所以我最好在一个声明中使用它

3 个答案:

答案 0 :(得分:1)

SELECT
    DATE(ride_date - interval 5 hour) as d,
    SUM(ride_earnings+ride_tips) as total,
    COUNT(id) as ride_count
FROM rides
WHERE time(ride_date) >= '17:00:00' 
   OR time(ride_date) <= '05:00:00' 
GROUP by d
order by total DESC

DATE(ride_date - interval 5 hour)会将早上时间(0:00 - 5:00)计算到前一天。 WHERE子句将确保只计算17:00 - 24:00和00:00 - 05:00之间的骑行。

更新

注意:请不要以使给定答案无效的方式更改您的问题。

SELECT
    DATE(ride_date - interval 12 hour) as d,
    SUM(ride_earnings+ride_tips) as total,
    COUNT(id) as ride_count
FROM rides
GROUP by d
order by total DESC

这里的前12个小时将计入前一天。在这种情况下不需要WHERE子句。

答案 1 :(得分:0)

制作一个临时表,其中包含您需要分组的日期。例如。(t_sql语法):

{{1}}

答案 2 :(得分:-1)

尝试:

SELECT DATE(ride_date) as d, SUM(ride_earnings+ride_tips) as total, COUNT(id) as ride_count FROM rides 
WHERE HOUR(ride_date) < 17 AND HOUR(ride_date) > 5
GROUP by d order by total DESC