Search code examples
sql-server-2014

combine duplicate records rows in sql into one row


I have duplicate records in one sql table . The rows has the same id but different values in different fields. how I can combine or merge those two rows or more into one row. Please help,

enter image description here


Solution

  • You can group those rows on certain fields by specifying a GROUP BY clause.

    In your case you would group on the ID column. For the columns you select in the SELECT clause that are not specified in the GROUP BY clause (i.e. columns other than ID), you will have to apply an aggregate function (e.g. SUM, MAX, MIN, ...).

    Edit - Simplified example based on your image:

    SELECT
        MasterID,
        CUSTNAME=MIN(CUSTNAME),
        ER1=MIN(ER1),
        ER1_BU=MIN(ER1_BU)
        -- For the other fields, the idea is the same
    FROM
        your_table
    GROUP BY
        MasterID
    ORDER BY
        MasterID;
    

    This example takes for each field the minimum of the fields for a particular MasterID. You did not really define what you mean by "merge". Perhaps you want the result to be a particular merge, you will have to clarify further if this example doesn't "merge" the rows like you want.