I’m having trouble getting a query to work where data is pulled from two tables, with a 3rd table in the middle. Let me show you what I mean.
*Table companies*
id int PK
name text
*Table projects*
id int PK
company_id int FK
project_name text
*Table hours_worked*
id int pk
user_id int FK
project_id int FK
hours float
date_worked datetime
*Table users*
id int PK
user_name text
Basically, what I need is a query that pulls the total amount of hours worked per company based on a user ID.
Note that the table_hours worked can have multiple submissions per day per project. For example, a few rows might look like
id project_id user_id hours date_worked
1 1 1 2 20-08-2012
2 1 1 1.5 20-08-2012
3 2 1 3 21-08-2012
4 2 2 12 22-08-2012
My desired result would be a query that returns something like this:
company_name total_hours
Bobs Kitchens 25
Mikes Bikes 67
Which returns the total number of hours worked per company (not project) for say, a user with the user ID of 1.
Here is the following query I’ve tried with no avail:
SELECT DISTINCT companies.name as company_name,
companies.id as company_id,
(
SELECT SUM(hours_worked.hours) FROM hours_worked
WHERE projects.id = hours_worked.project_id
AND projects.company_id = company_id
) as total_hours
FROM hoursworked, companies, projects
WHERE projects.company_id = company_id
AND projects.company_id = projects.company_id
AND hours_worked.user_id = 1
GROUP BY companies.id
This is giving me an odd result where a really weird number appears to be displaying for every total_hours field. 75 is not the correct total hours for any company!
company_name total_hours
Mikes Kitchen 75
Charlies Bikes 75
..... 75
Any help would be greatly appreciated!
I was such a fool..it was actually a lot easier than I expected. Hurray for over thinking.
The query I’ve used is: