I need to query this DB to get each row, but also the SUM of one of the values ββof the result column. I could use php to get the total value, but then I would need to run two loops to get the total (which is at the top above the results). Therefore, I would prefer the query to catch it and just make a βfinalβ line, but the only way I worked was to use a subquery, which is essentially a repetition of the original query. Is there a better way?
SELECT CONCAT(u.firstname, ' ', u.lastname ) name, u.id, s.description, s.shiftstart, s.shiftend, (SELECT SUM( TIME_TO_SEC( TIMEDIFF( shiftend, shiftstart ) ) ) /3600 FROM shifts WHERE id = '$user' AND DATE( shiftstart ) BETWEEN '$start' AND '$end') total FROM shifts s INNER JOIN users u ON ( s.id = u.id ) WHERE s.id = '$user' AND DATE( shiftstart ) BETWEEN '$start' AND '$end' ORDER BY shiftstart
The above work and outputs:
name id description shiftstart shiftend total Joe User joeuser Stuff 2009-01-05 07:45:00 2009-01-05 12:15:00 39.5000 Joe User joeuser Stuff 2009-01-05 13:00:00 2009-01-05 17:00:00 39.5000 Joe User joeuser Stuff 2009-01-06 07:45:00 2009-01-06 10:45:00 39.5000 Joe User joeuser Stuff 2009-01-06 10:45:00 2009-01-06 12:45:00 39.5000 Joe User joeuser Stuff 2009-01-06 13:30:00 2009-01-06 14:30:00 39.5000 Joe User joeuser Stuff 2009-01-06 14:30:00 2009-01-06 17:00:00 39.5000 Joe User joeuser Stuff 2009-01-07 09:45:00 2009-01-07 14:00:00 39.5000 Joe User joeuser Stuff 2009-01-07 15:00:00 2009-01-07 17:00:00 39.5000 Joe User joeuser Stuff 2009-01-08 08:00:00 2009-01-08 12:15:00 39.5000 Joe User joeuser Stuff 2009-01-08 13:15:00 2009-01-08 17:00:00 39.5000 Joe User joeuser Stuff 2009-01-09 07:45:00 2009-01-09 10:45:00 39.5000 Joe User joeuser Stuff 2009-01-09 11:45:00 2009-01-09 15:15:00 39.5000 Joe User joeuser Stuff 2009-01-09 15:15:00 2009-01-09 17:00:00 39.5000
This is what I need, but probably not the best way to get it.
source share