I’ve got three tables. Tickets, ticket history, and classification. I’d like to count how many tickets employees have completed, but broken down by classification.
As an example, Employee A worked on 3 tickets. The first two tickets were classified as bugs and the last was a feature. I’d like to query the database and select all tickets where the employee changed the state of the ticket.
Something like this:
Bug….. 2
Feature…… 1
UI….. 0
Request….. 0
Right now, all I can get is this:
Bug….. 2
Feature…… 1
Using this query:
SELECT c.id, c.description, count(c.id)
FROM classification c
LEFT JOIN ticket t on t.classification_id = c.id
LEFT JOIN ticket_history th on th.ticket_num = t.id
WHERE th.employee = '456'
AND th.from_state = '2' AND th.to_state = '3'
GROUP BY c.id
ORDER BY c.id
I’ve created a SQL Fiddle with sample data, but haven’t managed to find a solution yet.
The first problem is, that not all rows from the
classificationtable get selected, but only those with corresponding entries in the other two tables. That is because you’ve put some conditions that depend on entries in those tables in the WHERE clause. Basically, you’re doing a LEFT JOIN to address exactly this problem, but undermine this by putting the conditions in WHERE and not in LEFT JOIN … ON.The second problem is, that you count the number of classification while you actually want the number of tickets, right? So change
count(c.id)tocount(t.id)to get the right numbers.