Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

finchy70's avatar

Query to return totals by job number

I have a table that stores job numbers and hours as shown here.

Data table

I need to total all hours per job number for a specific period. Therefore period 1 result would look like this.

Data table and results

The data table extends to include 3 job number entries for each day.

Anyone able to help me build the query for this?

Thanks in advance.

0 likes
1 reply
Danieloplata's avatar

Hi @finchy70,

I'm not sure the way you've set up the database works very well - and it looks like you are making it complicated for yourself.

Would it not be a better idea to have a separate record for each job?

mon_job_number1_hours
mon_job_number2_hours
mon_job_number3_hours

Why not have 1 column for job_number and then another for hours

Doing it this way would allow you to make a query like:

/* Get total hours per job in Period 1 */

SELECT SUM(hours)
FROM your_database
WHERE period = 1
GROUP BY job_number

In eloquent it may look something like this:

App\Timesheet::groupBy('job_number')
    ->selectRaw('sum(hours)')
    ->where('period', '1')

https://laravel.com/docs/5.6/queries#aggregates

Please or to participate in this conversation.