I am trying to select the MAX of a COUNT grouping them by state (So one max for each distinct value in state). The count function works as intended.
SELECT c.id, c.name, t.name as type, COUNT(*) as count, c.state
FROM bookings_facilities f
JOIN bookings b
ON b.id = f.booking_id
JOIN clients c
ON c.id = b.client_id
JOIN client_types t
ON c.type = t.id
WHERE t.name = "School"
GROUP BY c.id
Here is the results,
I use the SQL statement below to try and choose the MAX of count grouping them by state.
SELECT *, MAX(z.count)
FROM (SELECT c.id, c.name, t.name as type, COUNT(*) as count, c.state
FROM bookings_facilities f
JOIN bookings b
ON b.id = f.booking_id
JOIN clients c
ON c.id = b.client_id
JOIN client_types t
ON c.type = t.id
WHERE t.name = "School"
GROUP BY c.id) z
GROUP BY z.state
Here is the results,
The 3 states, which appear only once in result 1
seems to be fine, but for the state, Selangor
, which appears twice in the first result, had some problems.
The SQL query selected the right MAX(Count) which is 6, but instead of returning id as 1027 it returned id as 1002 which only has count as 1 in the first result.
I have tried it with different sets of data but I can't seem to get the details of the actual MAX(Count) row.
Here is the database design for reference
Expected outcome is this, (Just the second row output needs to be changed).
Current Output Link