I am trying to write a sql for a table which storing geographic location data. That table has 4 columns - location id, parent id, display name and location type. Parent id will link with another record's location id in the same table and it may be null.
| location_id | parent_id | display_name | location_type |
|---|---|---|---|
| 1 | null | United States | Country |
| 2 | 1 | Texas, United States | States |
| 3 | 2 | Amarillo, Texas | City |
| 4 | null | Hong Kong | Country |
And I want to generate a report which have 3 columns: locationName,States,Country, the logic is like : while the record have a parent record, put its display name to States/Country Column based on its location type. But I have no idea how to do it using oracle sql.
May someone help me with this?
| locationName | States | Country |
|---|---|---|
| United States | null | United States |
| Texas, United States | Texas, United States | United States |
| Amarillo, Texas | Texas, United States | United States |
| Hong Kong | null | Hong Kong |
The logic will be like :
while(record still have parent id){
if(location type = "States"){
States column value = record's display_name
}
if(location type = "Country"){
Country column value = record's display_name
}
}
parentId. This will only return records in both table.