What you need here is a slightly elaborate SQL query. It will be made up of subqueries.
The first one is this (fiddle). It gets you the total number of door-open items for each name.
SELECT COUNT(*) total, name FROM stats GROUP BY name
The next one is this (fiddle). It gets you the number of opens per door and name.
SELECT COUNT(*) bydoor, name, door FROM stats GROUP BY name, door
The third one (fiddle) incorporates the second one, and gets you one line for each name, showing the door-opens.
SELECT name,
GROUP_CONCAT(CONCAT(bydoor,'X',' door ', door) ORDER BY bydoor DESC) details
FROM ( SELECT COUNT(*) bydoor,
name,
door
FROM stats
GROUP BY name, door
) s
GROUP BY name
Finally, you need a JOIN to tie those subqueries together, of this form.
SELECT t.name, t.total, d.details
FROM ( .... the first subquery ....) t
JOIN ( .... the second subquery .... ) d ON t.name = d.name
ORDER BY t.total DESC, t.name
All spelled out it looks like this (fiddle). You put it into your sql
variable and you're good to go. It's just a multiline string.
set sql {SELECT t.name, t.total, d.details
FROM (SELECT COUNT(*) total, name FROM stats GROUP BY name) t
JOIN ( SELECT name,
GROUP_CONCAT(CONCAT(bydoor,'X',' door ', door) ORDER BY bydoor DESC) details
FROM ( SELECT COUNT(*) bydoor,
name,
door
FROM stats
GROUP BY name, door
) s
GROUP BY name
) d ON t.name = d.name
ORDER BY t.total DESC, t.name}
So there's a query made of a bunch of nested queries.
There are some tricks here for you to learn as you get better at SQL data analysis.
- use of
GROUP BY
- query nesting, also known as subqueries. You can think of subqueries as virtual tables.
- (advanced)
GROUP_CONCAT
.