Currently, I have a table of class president results. I am trying to join rows as columns. Essentially, the result should provide an overview of the gender of the class president over different years.
Table, named results
:
+----+------+---------+--------+----------+-----------+-------+----------+-----------+
| id | year | faculty | winner | w_gender | w_percent | loser | l_gender | l_percent |
+----+------+---------+--------+----------+-----------+-------+----------+-----------+
| 1 | 2016 | Yellow | Tom | B | 56 | Jill | G | 46 |
| 2 | 2016 | Green | Susan | G | 52 | Sandy | G | 48 |
| 3 | 2016 | Purple | Carly | G | 51 | Jax | B | 49 |
| 4 | 2018 | Yellow | Tom | B | 56 | Jill | G | 46 |
| 5 | 2018 | Green | Ben | B | 52 | Sandy | G | 48 |
| 6 | 2018 | Purple | Amanda | G | 52 | James | B | 48 |
+----+------+---------+--------+----------+-----------+-------+----------+-----------+
Intended result:
+--------+------+------+
| group | 2016 | 2018 |
+--------+------+------+
| yellow | B | G |
| green | G | G |
| purple | G | B |
+--------+------+------+
Working MySQL query, modified from MySQL Join Multiple Rows as Columns:
SET @sql = NULL;
SELECT GROUP_CONCAT(DISTINCT CONCAT('MAX(CASE WHEN year = ', year, ' THEN w_gender END) AS ', CONCAT('`', year, '`')) ORDER BY year ASC) INTO @sql FROM results;
SET @sql = CONCAT('SELECT faculty, ', @sql, ' FROM results GROUP BY faculty');
PREPARE stmt FROM @sql;
EXECUTE stmt;
My current MySQL query is too complicated and occasionally triggers a MySQL timeout. So, how can I simplify this MySQL query?
UPDATE: The year
column should be dynamic and the query should work even if I add more results in future years.