How do I use today’s date as column title in Mysql

Asked

Viewed 36 times

3

I have the following table:

inserir a descrição da imagem aqui

Whereas today is 02/01/2019, while doing the pivot table below:

SELECT hora,
       CASE WHEN data = CURDATE() 
          THEN tarefa 
          ELSE NULL 
       END AS campo_1
  FROM tabela
 WHERE data BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 2 DAY)
 GROUP BY hora, data 
 ORDER BY hora

I get the following output:

inserir a descrição da imagem aqui

But I’d like to get:

inserir a descrição da imagem aqui

All help is welcome, thank you

  • See if this can help you.

  • Excellent Sam, from the idea I put together my code and it worked. Thanks!!!

1 answer

1


You can do it this way:

SET @curdate = CURDATE();
SET @sql = CONCAT('SELECT hora,
       CASE WHEN data = CURDATE() 
          THEN tarefa 
          ELSE NULL 
       END AS "', @curdate, '"
  FROM tabela
 WHERE data BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 2 DAY)
 GROUP BY hora, data 
 ORDER BY hora');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

So you put the current date first in a variable and then run the query.

A small example

Source

  • 1

    Thanks Wictor, solved, thank you very much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.