Merge multiple mysql rows having same id

2019-08-03 08:12发布

问题:

I have a table like this:

id  employee_id contract_id      month    year    d1     d2      d3
1          25        1                11     2011    1      01      01
2          16        5                11     2011    1      11      0
3          29        3                11     2011    1      001     100
1          25        4                11     2011    0      11      011

Suppose I need data for month='11' AND year='2011', then for all rows having the same 'employee_id', the data should merge like this:

id  employee_id contract_id      month    year    d1     d2      d3
1          25        1,4            11       2011    1,0    01,11   01,011
2          16        5              11       2011    1      11      0
3          29        3              11       2011    1      001     100

I was trying GROUP_CONCAT but couldn't figure out the query. Please help.

回答1:

SELECT
    id,
    employee_id,
    GROUP_CONCAT(contract_id SEPARATOR ',') AS contract_ids,
    `month`,
    `year`,
    GROUP_CONCAT(d1 SEPARATOR ',') AS d1s,
    GROUP_CONCAT(d2 SEPARATOR ',') AS d2s,
    GROUP_CONCAT(d3 SEPARATOR ',') AS d3s
FROM
    `table`
WHERE
    `month` = 11 AND `year` = 2011
GROUP BY
    employee_id


回答2:

   SELECT *, 
       GROUP_CONCAT(`d2`) as `d2`, 
       GROUP_CONCAT(`d3`) as `d3`, 
       GROUP_CONCAT(`contract_id`) as contract_id 
   FROM table WHERE month='11' AND year='2011' GROUP BY employee_id;