简体   繁体   中英

Combine two rows in a single row with the same ID name

Source Table with same Id need to combine them into single row

            +-----+-----+-----+-----+
            | Id  | ID1 | ID2 | ID3 |
            +-----+-----+-----+-----+
            | XYZ |     |   1 |   3 |
            | ZZZ |   4 |     |   5 |
            | ZZZ |     |   6 |     |
            | XYZ |   8 |    |     |
            +-----+-----+-----+-----+

What I want to achieve:

            +-----+-----+-----+-----+
            | Id  | ID1 | ID2 | ID3 |
            +-----+-----+-----+-----+
            | XYZ |   8 |   1 |   3 |
            | ZZZ |   4 |   6 |   5 |
            +-----+-----+-----+-----+

A simple aggregation should do the trick

Example

Select ID
      ,ID1 = max(ID1)
      ,ID2 = max(ID2)
      ,ID3 = max(ID3)
 From  YourTable
 Group By ID

Please check this link - MySQL get first non null value after group by

SELECT
    id,
    MAX(id1),
    MAX(id2),
    MAX(id3)
FROM
(
    SELECT
        id, id1, id2,id3
    FROM
        Test
) AS t

GROUP BY id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM