Search code examples
phpmysqlsortinggroup-bygroup-concat

Order Mysql query by Name and other fields


I have a question about MySQL. I have a Table with this fields:

  • WorkerName
  • Date
  • HoursWorked

Ok, if I do this Query:

SELECT WorkerName, Date, HoursWorked, SUM(HoursWorked) FROM myTable GROUP BY WorkerName

I have the field grouped by the Worker Name BUT with a only row. I want to show all days worked by this Worker in the same row, and the other Worker in another row.

In PHP actually have a While that shows all days worked, but only shows the Hours of the first day sorted.


Solution

  • You can use GROUP_CONCAT aggregate function:

    SELECT
      WorkerName,
      GROUP_CONCAT(Date) AS dates_worked,
      SUM(HoursWorked)
    FROM
      myTable
    GROUP BY
      WorkerName