Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL how to merge similar records into single row from same table?

I'm currently trying to clean up a database of mailing subscribers that a former employee created. I've been able to consolidate and fix most issues (primarily duplicates), but I have instances of subscribers with duplicate records because they are subscribed to multiple regions. What I want to do is merge those duplicate records into 1.

Here is an redacted actual example of a duplicate record that I'd like to merge:

id     first     last    address    truck    machinery    gl    ne    nw
------------------------------------------------------------------------
1      Chuck     G....   12 Lorem   1                     1
2      Chuck     G....   12 Lorem            1                        1
3      Chuck     G....   12 Lorem            1                  1

And I'd like to merge the 2 into 1 record, and delete all duplicates (some have up to 9 duplicates) like this:

id     first     last    address    truck    machinery    gl    ne    nw
------------------------------------------------------------------------
1      Chuck     G....   12 Lorem   1        1            1     1     1
like image 316
Noah Yamen Avatar asked Jan 06 '16 18:01

Noah Yamen


People also ask

How do I combine values from multiple rows into one row in SQL?

You can concatenate rows into single string using COALESCE method. This COALESCE method can be used in SQL Server version 2008 and higher. All you have to do is, declare a varchar variable and inside the coalesce, concat the variable with comma and the column, then assign the COALESCE to the variable.

How do I combine similar data in SQL?

To combine data from two tables we use the SQL JOIN command, which comes after the FROM command. Database tables are used to organize and group data by common characteristics or principles. Often, we need to combine elements from separate tables into a single tables or queries for analysis and visualization.


1 Answers

Use Group By and Max/Min Aggregate

SELECT id, 
       first, 
       last, 
       address, 
       Max(truck)     AS truck, 
       Max(machinery) AS machinery, 
       Max(gl)        AS gl, 
       Max(ne)        AS ne, 
       Max(nw)        AS nw 
FROM   yourtable 
GROUP  BY id, 
          first, 
          last, 
          address 
like image 53
Pரதீப் Avatar answered Oct 26 '22 11:10

Pரதீப்