Search code examples
mysqlsqlconcatenationgroup-concat

group concat a field based on 2 same data in another field


Given this table,

+----+------------------+-----------+----------+
| id | Doctor name      | firsttime | lasttime |
+----+------------------+-----------+----------+
|  1 | Dr. Abdurahman   | 12:00:00  | 21:00:00 |
|  2 | Dr. Sultan Hamid | 12:00:00  | 21:00:00 |
|  3 | Dr. Susanti      | 12:00:00  | 21:00:00 |
|  4 | Dr. Siparman     | 12:00:00  | 21:00:00 |
|  5 | Dr. Ramah        | 12:00:00  | 21:00:00 |
|  6 | Drs. Susanto     | 13:00:00  | 22:00:00 |
|  7 | Dr. Budiarjo     | 13:00:00  | 22:00:00 |
|  8 | Dr. Antonius     | 13:00:00  | 22:00:00 |
|  9 | Dr. Wahid Bahyu  | 13:00:00  | 22:00:00 |
+----+------------------+-----------+----------+

expected
+----+--------------------------------------------+-----------+----------+
| id | Doctor name                                | firsttime | lasttime |
+----+--------------------------------------------+-----------+----------+
|  1 | Dr. Abdurahman, Dr. Sultan Hamid, etc      | 12:00:00  | 21:00:00 |
|  2 | Drs. Susanto, Dr. Budiarjo, etc            | 13:00:00  | 22:00:00 |
+----+--------------------------------------------+-----------+----------+

what i'm expecting is to select the table based on the first time and last time with group concat on Doctor name. So if there is the same firstdate AND lastdate it will be included in the group concat

Note: the first date and last date is random, ignore the etc, i want it full name of doctor


Solution

  • use GROUP_CONCAT

    SELECT firstdate,lastdate,
        GROUP_CONCAT(doctorname)
    FROM
        table group by firstdate,lastdate