Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SQL: Split rows out of values from multiple columns

I have a table that looks something like this:

ID State Name State Value City Name City Value
1 Indiana 8.0 Gary 5.0
2 Florida 9.0 Miami 2.0

I would like to output a table that looks something like this:

ID Name Value
1 State, Indiana 8.0
2 City, Gary 5.0
3 State, Florida 9.0
4 City, Miami 2.0

I was trying to solve by groupby but that is just outputting unique rows in their entirety not creating unique rows based off multiple columns unique values.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use union all:

select concat('State, ', StateName) as Name, StateValue as Value
from table_name
union all
select concat('State, ', CityName) as Name, CityValue as Value
from table_name;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading