0

I have a MySQL table for data containing earnings for taxi / uber rides with the following fields:

id
ride_date 
ride_earnings
ride_tips

I am trying to get a list of the most "profitable" dates, I can do:

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

But I need to group them as all rides from 12pm on one day - 12pm the next day. Thanks in advance!

EDIT: Changed from 12p - 12p to make it more simple

EDIT2: Also, I should have stated this but i will be pulling this data through PHP so I would preferably need it in one statement

TheJoester
  • 11
  • 4

3 Answers3

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) will count the morning hours (0:00 - 5:00) to the day before. The WHERE clause will ensure that only rides from 17:00 - 24:00 and from 00:00 - 05:00 will be counted.

Update

Note: Please don't change your question in a way that would invalidate given answers.

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

Here the first 12 hours of the day will be counted to the day before. The WHERE clause is not needed in this case.

Community
  • 1
  • 1
Paul Spiegel
  • 30,925
  • 5
  • 44
  • 53
0

make a temporary table containing the dates you need to group by. eg.(t_sql syntax) :

declare @startDate date, @endDate.
select @startDate=min(ride_date), @endDate=max(ride_date) from rides


declare @tempDate date=dateAdd(dd,-1,@startDate)
declare @dateIntervals table(starDT dateTime, endDT dateTime)
while(@tempDate<@endDate) begin
    insert into @dateIntervals
    values(cast(@tempDate as DateTime)+'05:00:00',cast(dateAdd(dd,1,@tempDate) as DateTime)+'05:00:00')
    select @tempDate=dateAdd(dd, 1,@tempDate)
end

select t1.startDT as d, SUM(ride_earnings+ride_tips) as total, COUNT(id) as ride_count 
from @dateIntervals t1
left join rides t2 on t2.ride_date>=t1.startDT and t2.ridetDate<t2.endDT
GROUP by d 
order by total DESC
user3532232
  • 257
  • 8
  • 19
-1

try:

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
Gustavo Topete
  • 1,246
  • 1
  • 9
  • 15