Making SQL query dynamic
The dynamic sql below is building the conditional sums from on a reference table with the categories.
SET @sums := ( SELECT GROUP_CONCAT( CONCAT( ', SUM(CASE WHEN category_id = ', category_id, ' AND `status` < 80 THEN 1 ELSE 0 END)', ' AS `', category_name, ' En cours`', CHAR(10), ', SUM(CASE WHEN category_id = ', category_id, ' AND `status` >= 80 THEN 1 ELSE 0 END)', ' AS `', category_name, ' Resolu`', CHAR(10) ) ORDER BY category_id SEPARATOR '') as sums FROM categories ); SET @dynsql := CONCAT('SELECT', CHAR(10), ' bug.project_id', CHAR(10), ', COUNT(bug.id) AS Total', CHAR(10), @sums, 'FROM bugs bug', CHAR(10), 'GROUP BY bug.project_id', CHAR(10), 'HAVING COUNT(bug.id) > 0;'); -- SELECT @dynsql AS dynsql; PREPARE dyn_stmt FROM @dynsql; EXECUTE dyn_stmt; DEALLOCATE PREPARE dyn_stmt;
project_id | Total | Conneries En cours | Conneries Resolu | Bugs En cours | Bugs Resolu | Ameliorations En cours | Ameliorations Resolu |
---|---|---|---|---|---|---|---|
0 | 5 | 1 | 0 | 1 | 1 | 1 | 1 |
Demo on db<>fiddle here