mysql – Dynamic column alias

The answer is simple: It is not possible in SQL. Column aliases are constants. You would have to create the query dynamically to achieve what you want:

SET @column_alias1 := NOW() - INTERVAL 1 WEEK;
SET @column_alias2 := NOW() - INTERVAL 2 WEEK;
SET @query := CONCAT('SELECT SUM(...) AS `', @column_alias1, '`, SUM(...) AS `', @column_alias2, '` FROM ...');
PREPARE dynamic_statement FROM @query;
EXECUTE dynamic_statement;

Leave a Comment