I have table called location
that looks like this:
| zip_code | city | state |
| -------- | ------------- | ----- |
| 01108-2005 | | |
| 02130-1911 | Jamaica Plain | MA |
| 02130-1911 | Jamaica Plain | |
| 02138-1557 | Cambridge | MA |
| 02138-1557 | | MA |
| 02138-1557 | | |
| 02370-2509 | | MA |
| 02370-2509 | | MA |
I only want unique zip codes and as many corresponding city/state values as possible. For example:
- the zip code 01108-2005 is already unique, so I will keep it even though there is no city or state.
- the zip code 02138-1557 at least has state in one record, but not in the other, so I want to only keep the record that has a state.
- the zip code 02130-1911 has a record with only city as well as a record with both city and state. I want the record with both city and state, for it is the most complete.
I've tried the following code:
SELECT DISTINCT zip_code, city, state
FROM location
ORDER BY zip_code, city DESC, state DESC
which treats each record as distinct. Is there a way to only select the most complete records, or to merge all records that share a zip code?
I am new to StackOverflow (and to MySQL) so any tips on how I can make my question easier to understand are appreciated.