Search code examples
mysqlsqlcase-when

How to use CASE WHEN statement with multiple id


I have a problem to use CASE WHEN statement in my problem. I have data with multiple id but each multiple id have a different problem.

I want to display each problem from each same id in column not row. I tried using case when and group by but the 2nd problem not display

This is my data :

ID Ticket Problem Date
400 A OFF 2020-12-30 07:00:00
400 A OUT 2020-12-30 09:00:00
410 A OFF 2020-12-30 09:00:00
420 B OUT 2020-12-30 07:00:00
430 B OUT 2020-12-30 09:00:00
430 B OUT 2020-12-30 13:00:00

I want to display it like this

ID Ticket 2020-12-30 07:00:00 2020-12-30 09:00:00 2020-12-30 13:00
400 A OFF OUT -
410 A - OFF -
420 B OUT - -
430 B OUT - OUT

Thank you


Solution

  • You can use conditional aggregation as follows:

    Select ticket,
           max(case when date = your_date1 then problem end) as date_1_problem,
           max(case when date = your_date2 then problem end) as date_2_problem,
           max(case when date = your_date3 then problem end) as date_3_problem
      From your_table t
    Group by ticket;
    

    Please note that you habe to provide the values of date1, date2 and date3 in this query.