合并具有相同id的多个mysql行

时间:2012-03-25 15:19:40

标签: mysql join merge rows

我有一张这样的表:

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

假设我需要month ='11'和year ='2011'的数据,那么对于具有相同'employee_id'的所有行,数据应合并如下:

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

我正在尝试GROUP_CONCAT,但无法弄清楚查询。请帮忙。

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:1)

   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;