Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
OldMySQLUser
Constraint Violating Yak Guru
301 Posts |
Posted - 2008-02-08 : 10:24:40
|
| I have four tables:table1-------code descriptionB Black sweaterC Cream sweaterR Red sweaterTable2------code descriptionG Green sweaterB Sweater, BlackW White sweaterTable3------code descriptionO orange sweaterP purple sweaterTable4------code descriptionM Mauve sweaterL Lilac sweaterI wish to merge all four tables into a new (master) table where there are no duplicate codes. After trying:INSERT INTO table5SELECT * FROM table1UNIONSELECT * FROM table2UNIONSELECT * FROM table3UNIONSELECT * FROM table4I got:C Cream sweaterR Red sweaterG Green sweaterB Sweater, BlackB Black sweaterW White sweaterO orange sweaterP purple sweaterM Mauve sweaterL Lilac sweaterbut I don't want duplicate codes so how can I correct me SQL query please? |
|
|
Qualis
Posting Yak Master
145 Posts |
Posted - 2008-02-08 : 10:46:59
|
| Technically, those ARE distinct records. If your form is ALWAYS either [Color][space][Item] OR [Item][comma][space][Color], then you can write logic to deal with that. You can use this for the above 2 forms:Select code, Case When CharIndex(', ', description) > 0 Then SubString(description, CharIndex(', ', description) + 2, 500) + ' ' + Left(description, CharIndex(', ', description) - 1) Else description End As descriptionFrom Table1Union... |
 |
|
|
OldMySQLUser
Constraint Violating Yak Guru
301 Posts |
Posted - 2008-02-08 : 11:04:47
|
| OK, I understand. Thanks for your example.If I were to ignore the description situation altogether, how would I select only one of any record(s) from the other tables whos code were the same for insertion into the new, merged, table? So if each table contained a record whos code was 'B'i.e.table1------code descriptionB Black sweatertable2------code descriptionB Sweater, blacktable3------code descriptionB Sweater which is blacktable4------code descriptionB Almost black sweaterThe new table would just contain ONE of the 'B' code records ( I don't really care which, as long as I have a 'B' code item)? |
 |
|
|
mwjdavidson
Aged Yak Warrior
735 Posts |
Posted - 2008-02-08 : 11:12:09
|
If you really don't care which description gets returned:SELECT Code, MIN(Description)FROM ( SELECT Code, Description FROM table1 UNION SELECT Code, Description FROM table2 -- etc. ) AS tGROUP BY Code Mark |
 |
|
|
OldMySQLUser
Constraint Violating Yak Guru
301 Posts |
Posted - 2008-02-08 : 12:08:57
|
| That nailed it.Please accept my grateful thanks. |
 |
|
|
|
|
|
|
|