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
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With