I have table with positions
tbl_positions
id position
1 Driver
2 Lobby
3 Support
4 Constructor
and in other table i have users
EDIT:
tbl_workers
id name position position2 status
1 John 2 3 4
2 Mike 3 2 2
3 Kate 2 0 3
4 Andy 1 0 0
i do request of positions
SELECT p.id,
p.position,
SUM(CASE w.Status WHEN 2 THEN 1 ELSE 0 END) AS booked,
SUM(CASE w.Status WHEN 3 THEN 1 ELSE 0 END) AS placed
FROM tbl_positions AS p LEFT JOIN tbl_workers AS w
ON w.position=p.id
GROUP BY p.id, p.position
I need output like this in single query.
Position booked placed
Driver 0 0
Lobby 1 2
Support 0 2
Constructor 0 0
I need to evalate both field positon1 and position2 instead of one. I think its easy to modify it but i cannot find the right solution please help.
EDIT : Added status 4
Instead of joining to
tbl_workersyou could join to its unpivoted variation wherepositionandposition2would be in the same column but in different rows.Here’s how the unpivoting might look like:
Here’s the entire query, which is basically your original query with the above query substituting for the
tbl_workerstable:UPDATE
This is a modified script according to additional request in comments:
The idea is to substitute the
4status in the subselect with3or2depending on whether we are currently to pullpositionorposition2as the unifiedposition. The outer select keeps using the same logic as before.