如何将具有相同ID的多行合并为一行?

时间:2018-04-02 21:01:31

标签: mysql sql sql-server tsql

如何将具有相同ID的多个行合并为一行。

我有桌子:

+----+------+------+------+
| ID |  A   |  B   |  C   |
+----+------+------+------+
|  1 | 123  | 31   | 456  |
|  1 | 412  | NULL | 1    |
|  2 | 567  | 38   | 4    |
|  2 | 567  | NULL | NULL |
|  3 | 2    | NULL | NULL |
|  3 | 5    | NULL | NULL |
|  4 | 6    | 1    | NULL |
|  4 | 8    | NULL | 5    |
|  4 | NULL | NULL | 5    |
+----+------+------+------+

我想要桌子: 我有桌子:

+----+-----+------+------+-----+------+------+------+------+----+
| ID |  A  |  B   |  C   | A2  |  B2  |  C2  |  A3  |  B3  | C3 |
+----+-----+------+------+-----+------+------+------+------+----+
|  1 | 123 | 31   | 456  | 412 | NULL | 1    |      |      |    |
|  2 | 567 | 38   | 4    | 567 | NULL | NULL |      |      |    |
|  3 |   2 | NULL | NULL |   5 | NULL | NULL |      |      |    |
|  4 |   6 | 1    | NULL |   8 | NULL | 5    | NULL | NULL |  5 |
+----+-----+------+------+-----+------+------+------+------+----+

1 个答案:

答案 0 :(得分:0)

试试这个: -

1: - 请更改数据表结构以禁止空值。

enter image description here

  1. 查询: -

    SELECT 
        GROUP_CONCAT(if (`A` ='0', 'NOVAL', `A`)SEPARATOR '----') as A,
        GROUP_CONCAT(if (`B` ='0', 'NOVAL', `B`)SEPARATOR '----') as B,
        GROUP_CONCAT(if (`C` ='0', 'NOVAL', `C`)SEPARATOR '----') as C 
    FROM que1
    GROUP BY id
    
  2. 现在您可以使用mysql_fetch_array

    获取值

    enter image description here