Home > Software design >  Combine two rows in a single row with the same ID name
Combine two rows in a single row with the same ID name

Time:01-19

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 |
             ----- ----- ----- ----- 

CodePudding user response:

A simple aggregation should do the trick

Example

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

CodePudding user response:

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
  •  Tags:  
  • Related