How can I separate a string into columns, if I have multiple rows and the strings are of different length in SQL?

GabyB. :

The question says:

Retrieve all unique countries of all publishers.

The column from where I'm supposed to retrieve the countries is the following:

Table: Publisher

Column: Address

Rows:

  • Hoboken, New Jersey, United States
  • London, United Kingdom
  • New York, New York, United States
  • New York, New York, United States
  • New York, New York, United States

Now, I understand that the answer is asking me is to display: Unites States, United Kingdom. However, the countries are in a string with city, state and country in the case of USA and city and country in the case of UK.

I don't know how to separate the column address into columns, so then I can retrieve the unique values for the countries.

I tried using SUBSTR() and SUBSTRING(), but I have to write the string inside, and I don't know how to write it all into one function.

sirine :

You can use distinct substring_index.

select distinct substring_index(Address,',',-1) from publisher;

You can find more explanation here

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=26619&siteId=1