I have some tables roughly like so:
Client:
id
name
Employee
id
name
Email
id
to : Client [ForeignKey]
from : Employee [ForeignKey]
EmailStats (Tracks the stats for a particular single email)
id
email : Email [OneToOne]
curse_words : 10
What I want to do: I want to fetch all the employees that have written at least one email to a single client, along with the number of times they’ve cursed in any of their emails to that single client, i.e. for a particular Client return
[
('name' : 'Paul', 'total_curses' : 255),
('name' : 'Mary', 'total_curses' : 10),
]
What I’ve tried:
My understanding of SQL is quite weak as I’m used to using ORM’s. I’m having trouble understanding how the normal retrieval of Employees links into the counting of the curse words. Here’s what I’ve done (be kind!):
SELECT DISTINCT (
SELECT SUM(EmailStats.curse_words)
FROM EmailStats
INNER JOIN (
SELECT Email.id
FROM Email
INNER JOIN Employee
ON Email.from = Employee.id
WHERE Email.to = 5 // Assuming 5 is the client's id
) filtered_emails ON EmailStats.email = filtered_emails.id
) AS 'total_curses', Employee.name
FROM Employee
INNER JOIN Email
ON Email.from = Employee.id
WHERE Email.to = 5 // Assuming 5 is the client's id
ORDER_BY 'total_curses'
This isn’t working – it seems to fetch the correct Employees (those who have sent to the Client) but the curses count seems to be the total for all emails to that Client instead of just those curses from that Employee.
I’ve got a feeling that I’m gravely misunderstanding something here, so if anyone could provide an example of how to succesfully go about this I’d appreciate some pointers.
You want to group the result of joining your tables: