Reputation: 817
That title may not make sense, I'm not sure how to ask what I'm trying to do in a single sentence...
I have a MySQL table like this:
| id | user | team | month | result |
|----|-------|--------|-------|--------|
| 1 | Joe | red | sept | 100 |
| 2 | Joe | red | oct | 40 |
| 3 | Jim | red | sept | 70 |
| 4 | Jim | red | oct | 50 |
| 5 | Susy | red | sept | 40 |
| 6 | Tim | blue | sept | 60 |
| 7 | Tim | blue | oct | 100 |
| 8 | Betty | blue | sept | 70 |
| 9 | Dave | blue | sept | 20 |
| 10 | Stan | green | oct | 40 |
| 11 | Alan | green | sept | 80 |
| 12 | Tina | green | oct | 100 |
| 13 | Tina | green | sept | 30 |
| 14 | Rick | yellow | oct | 50 |
| 15 | Ellen | yellow | oct | 60 |
Ultimately I'm trying to output an HTML table that shows a total number of users who have a result greater than 50 organized by team and month.
Here's the query I'm running right now:
SELECT team, month, count(*)
FROM example
WHERE result >= 50
GROUP BY team, month
Which returns this:
| team | month | count(*) |
|--------|-------|----------|
| blue | oct | 1 |
| blue | sept | 2 |
| green | oct | 1 |
| green | sept | 1 |
| red | oct | 1 |
| red | sept | 2 |
| yellow | oct | 2 |
But in my HTML table I want to list out months as columns (and add a total column). So an HTML table that renders like this (ignore the sorting, it's arbitrary):
| Team | sept | oct | Total |
|--------|------|-----|-------|
| red | 2 | 1 | 3 |
| blue | 2 | 1 | 3 |
| green | 1 | 1 | 2 |
| yellow | 0 | 2 | 2 |
Can I work with the query result I have and somehow manipulate it into the end format in the PHP/HTML? Or do I need to change the way I'm querying in the first place?
*Editing to change the HTML table output example - I want this to be dynamic so that as more months are added to original table the resulting HTML table can expand horizontally.
Upvotes: 1
Views: 2116
Reputation: 69789
The basic SQL you need is:
SELECT Team,
COUNT(CASE WHEN Month = 'Sept' THEN 1 END) AS Sept,
COUNT(CASE WHEN Month = 'Oct' THEN 1 END) AS oct,
COUNT(*) AS Total
FROM T
GROUP BY Team;
If you don't know the number of columns you need you will need to do it dynamically with a prepared statement'
SET @sql = NULL;
SELECT GROUP_CONCAT(DISTINCT
CONCAT(
'COUNT(CASE WHEN Month = ''',
Month,
''' THEN 1 END) AS ',
Month
)
)
INTO @sql
FROM T;
SET @sql = CONCAT('SELECT Team, ', @sql, ', COUNT(*) AS Total FROM T GROUP BY Team');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
Upvotes: 2