How do I Group Text in Mysql

Asked

Viewed 130 times

0

I’ve tried to find a solution to this case, and I need your help.

I have the following table:

hora    data        tarefa
10:00   02/01/19    A
10:00   03/01/19    B
11:00   02/01/19    C

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
        ,   CASE WHEN data = DATE_ADD(CURDATE(), INTERVAL 1 DAY) 
            THEN tarefa
            ELSE NULL
            END AS campo_2
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:

hora    Campo_1     Campo_2
10:00   A           
10:00               B
11:00   C

However, I would like to get:

hora    Campo_1     Campo_2
10:00   A           B
11:00   C
  • IN SHORT, I CAN’T GROUP THE TIME TO SHOW ONLY ONE LINE AT 10:00, AND TASKS A AND B ON THIS LINE, BELOW THEIR RESPECTIVE DATES.

Thank you in advance for any solution.

  • You have checked whether the GROUP_CONCAT(expr) function does not meet your needs?

  • I used GRUP_CONCAT, but it returns the following output: 10:00, 10:00 A, ,B Not quite what I expected. Thanks

2 answers

4

I believe a sub-select can handle:

select 
     hora as horaH, 
     tarefa, 
     (select tarefa from tabela where data= DATE_ADD(CURDATE(), INTERVAL 1 DAY)  and hora = horaH) 
from tabela where data = CURDATE() 

This fits the case in question, I don’t know if you can have more than one task at the same time and day, but then it’s a matter of you adapting the code.

  • Carla, for this example table works, but if you add one more task on the same day as task B, it generates the error: the sub-query returns more than one record. Thanks for the suggestion.

0

My good friend Alan answered this question, as he has no account, I answered the question:

SELECT  hora,
    MAX(CASE WHEN data = curdate() THEN tarefa ELSE NULL END) as campo_1,
    MAX(CASE WHEN data = DATE_ADD(curdate(), INTERVAL 1 DAY) THEN tarefa ELSE NULL END) as campo_2
FROM tabela 
where data between curdate() and DATE_ADD(curdate(), INTERVAL 2 DAY)
GROUP BY hora
ORDER BY hora

Thank you all.

Browser other questions tagged

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