<p>I've been handed a table with about 18000 rows. Each record describes the location of one customer. The issue is, that when the person created the table, they did not add a field for "Company Name", only "Location Name," and one company can have many locations.</p>

<p>For example, here are some records that describe the same customer:</p>

<p><strong>Location Table</strong></p>

<pre><code> ID  Location_Name     
 1   TownShop#1        
 2   Town Shop - Loc 2 
 3   The Town Shop     
 4   TTS - Someplace   
 5   Town Shop,the 3   
 6   Toen Shop4        
</code></pre>

<p>My goal is to make it look like:</p>

<p><strong>Location Table</strong></p>

<pre><code> ID  Company_ID   Location_Name     
 1   1            Town Shop#1       
 2   1            Town Shop - Loc 2 
 3   1            The Town Shop     
 4   1            TTS - Someplace   
 5   1            Town Shop,the 3   
 6   1            Toen Shop4        
</code></pre>

<p><strong>Company Table</strong></p>

<pre><code> Company_ID  Company_Name  
 1           The Town Shop 
</code></pre>

<p>There is no "Company" table, I will have to generate the Company Name list from the most descriptive or best Location Name that represents the multiple locations.</p>

<p>Currently I am thinking I need to generate a list of Location Names that are similar, and then and go through that list by hand.</p>

<p>Any suggestions on how I can approach this is appreciated.</p>

<p><strong>@Neall, Thank you for your statement, but unfortunately, each location name is distinct, there are no duplicate location names, only similar. So in the results from your statement "repcount" is 1 in each row.</strong></p>

<p><strong>@yukondude, Your step 4 is the heart of my question.</strong></p>

[{'answer_id': 6119, 'author': 'Neall', 'author_id': 619, 'author_profile': 'https://Stackoverflow.com/users/619', 'pm_score': 1, 'selected': False, 'text': '<p>I\'ve had to do this before. The only real way to do it is to manually match up the various locations. Use your database\'s console interface and grouping select statements. First, add your "Company Name" field. Then:</p>\n\n<pre><code>SELECT count(*) AS repcount, "Location Name" FROM mytable\n WHERE "Company Name" IS NULL\n GROUP BY "Location Name"\n ORDER BY repcount DESC\n LIMIT 5;\n</code></pre>\n\n<p>Figure out what company the location at the top of the list belongs to and then update your company name field with an UPDATE ... WHERE "Location Name" = "The Location" statement.</p>\n\n<p>P.S. - You should really break your company names and location names out into separate tables and refer to them by their primary keys.</p>\n\n<p>Update: - Wow - no duplicates? How many records do you have?</p>\n'}, {'answer_id': 6120, 'author': 'Jake McGraw', 'author_id': 302, 'author_profile': 'https://Stackoverflow.com/users/302', 'pm_score': 2, 'selected': True, 'text': '<p>Please update the question, do you have a list of CompanyNames available to you? I ask because you maybe able to use Levenshtein algo to find a relationship between your list of CompanyNames and LocationNames.</p>\n\n<hr>\n\n<p><strong>Update</strong></p>\n\n<blockquote>\n  <p>There is not a list of Company Names, I will have to generate the company name from the most descriptive or best Location Name that represents the multiple locations.</p>\n</blockquote>\n\n<p>Okay... try this:</p>\n\n<ol>\n<li>Build a list of candidate CompanyNames by finding LocationNames made up of mostly or all alphabetic characters. You can use <a href="http://us2.php.net/manual/en/book.pcre.php" rel="nofollow noreferrer">regular expressions</a> for this. Store this list in a separate table.</li>\n<li>Sort that list alphabetically and (manually) determine which entries should be CompanyNames.</li>\n<li>Compare each CompanyName to each LocationName and come up with a match score (use <a href="http://us2.php.net/manual/en/function.levenshtein.php" rel="nofollow noreferrer">Levenshtein</a> or some other string matching algo). Store the result in a separate table.</li>\n<li>Set a threshold score such that any MatchScore &lt; Threshold will not be considered a match for a given CompanyName.</li>\n<li>Manually vet through the LocationNames by CompanyName | LocationName | MatchScore, and figure out which ones actually match. Ordering by MatchScore should make the process less painful.</li>\n</ol>\n\n<p>The whole purpose of the above actions is to automate parts and limit the scope of your problem. It\'s far from perfect, but will hopefully save you the trouble of going through 18K records by hand.</p>\n'}, {'answer_id': 6124, 'author': 'Mark Renouf', 'author_id': 758, 'author_profile': 'https://Stackoverflow.com/users/758', 'pm_score': 0, 'selected': False, 'text': '<p>I was going to recommend some complicated token matching algorithm but it\'s really tricky to get right and if you\'re data does not have a lot of correlation (typos, etc) then it\'s not going to give very good results.</p>\n\n<p>I would recommend you submit a job to the <a href="http://www.mturk.com/mturk/welcome" rel="nofollow noreferrer">Amazon Mechanical Turk</a> and let a human sort it out.</p>\n'}, {'answer_id': 6129, 'author': 'yukondude', 'author_id': 726, 'author_profile': 'https://Stackoverflow.com/users/726', 'pm_score': 0, 'selected': False, 'text': '<p>Ideally, you\'d probably want a separate table named Company and then a company_id column in this "Location" table that is a foreign key to the Company table\'s primary key, likely called id. That would avoid a fair bit of text duplication in this table (over 18,000 rows, an integer foreign key would save quite a bit of space over a varchar column).</p>\n\n<p>But you\'re still faced with a method for loading that Company table and then properly associating it with the rows in Location. There\'s no general solution, but you could do something along these lines:</p>\n\n<ol>\n<li>Create the Company table, with an id column that auto-increments (depends on your RDBMS).</li>\n<li>Find all of the unique company names and insert them into Company.</li>\n<li>Add a column, company_id, to Location that accepts NULLs (for now) and that is a foreign key of the Company.id column.</li>\n<li>For each row in Location, determine the corresponding company, and UPDATE that row\'s company_id column with that company\'s id. This is likely the most challenging step. If your data is like what you show in the example, you\'ll likely have to take many runs at this with various string matching approaches.</li>\n<li>Once all rows in Location have a company_id value, then you can ALTER the Company table to add a NOT NULL constraint to the company_id column (assuming that every location <em>must</em> have a company, which seems reasonable).</li>\n</ol>\n\n<p>If you can make a copy of your Location table, you can gradually build up a series of SQL statements to populate the company_id foreign key. If you make a mistake, you can just start over and rerun the script up to the point of failure.</p>\n'}, {'answer_id': 6428, 'author': 'yukondude', 'author_id': 726, 'author_profile': 'https://Stackoverflow.com/users/726', 'pm_score': 0, 'selected': False, 'text': "<p>Yes, that step 4 from my previous post is a doozy.</p>\n\n<p>No matter what, you're probably going to have to do some of this by hand, but you may be able to automate the bulk of it. For the example locations you gave, a query like the following would set the appropriate company_id value:</p>\n\n<pre><code>UPDATE  Location\nSET     Company_ID = 1\nWHERE   (LOWER(Location_Name) LIKE '%to_n shop%'\nOR      LOWER(Location_Name) LIKE '%tts%')\nAND     Company_ID IS NULL;\n</code></pre>\n\n<p>I believe that would match your examples (I added the <code>IS NULL</code> part to not overwrite previously set Company_ID values), but of course in 18,000 rows you're going to have to be pretty inventive to handle the various combinations.</p>\n\n<p>Something else that might help would be to use the names in Company to generate queries like the one above. You could do something like the following (in MySQL):</p>\n\n<pre><code>SELECT  CONCAT('UPDATE Location SET Company_ID = ',\n        Company_ID, ' WHERE LOWER(Location_Name) LIKE ',\n        LOWER(REPLACE(Company_Name), ' ', '%'), ' AND Company_ID IS NULL;')\nFROM    Company;\n</code></pre>\n\n<p>Then just run the statements that it produces. That could do a lot of the grunge work for you.</p>\n"}]
['https://Stackoverflow.com/questions/6110', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/754/']