开发者

Select each clients' name and the total amount of time they have spent in sessions

I have the following tables setup in a MySQL database:

Client:
id
name

Session:
id
service_id
date

Attendance:
id
client_id
session_id

Service:
id
duration

Clients have a many to many relationship with Sessions through the Attendance table.

I am trying to write a query which will return each clients' name and the total amount of time they have spent in sessions, like this:

Name       Total Time (Mins)
Person A   200
Person B   500
Person C   100

So far my query looks like this:

SELECT 
(SELECT SUM(services.d开发者_如何学Curation) 
FROM services
INNER JOIN sessions
ON sessions.service_id = services.id
INNER JOIN attendances
ON attendances.session_id = session.id
INNER JOIN clients
ON clients.id = attendances.client_id
GROUP BY clients.id) AS total_duration,
client.name 
FROM clients

However, this returns no results. Whereas, if I run either part of the query in isolation I get the data I need, ie:

SELECT name FROM clients

OR

SELECT SUM(services.duration) 
FROM services
INNER JOIN sessions
ON sessions.service_id = services.id
INNER JOIN attendances
ON attendances.session_id = session.id
INNER JOIN clients
ON clients.id = attendances.client_id
GROUP BY clients.id

Can anyone see a reason why it would not be working when I combine the two?


You are missing a WHERE condition in correlated query. I rewrote your query with only joins to make it more readable:

SELECT c.name, sum(srv.duration)
FROM clients c
    JOIN attendances a ON a.client_id = c.id
    JOIN sessions s ON s.id - a.session_id
    JOIN services srv ON srv.id = s.service_id
GROUP BY c.name
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜