Merge multiple mysql rows having same id

…衆ロ難τιáo~ 提交于 2019-12-08 07:32:47

问题


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;


来源:https://stackoverflow.com/questions/9861298/merge-multiple-mysql-rows-having-same-id

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!