WITH
district_table AS (
SELECT
code AS d_code,
description AS d_description,
parent AS d_parent
FROM
`propertyguru-datalake-v0.propertydb_staging.my_geographic_area`
WHERE type_code = 'D'
AND country = 'MY'
),
area_table AS (
SELECT
code AS a_code,
description AS a_description,
parent AS a_parent
FROM
`propertyguru-datalake-v0.propertydb_staging.my_geographic_area`
WHERE type_code = 'A'
AND country = 'MY'
),
region_table AS (
SELECT
code AS r_code,
description AS r_description
FROM
`propertyguru-datalake-v0.propertydb_staging.my_geographic_area`
WHERE type_code = 'L'
AND country = 'MY'
),
final_table AS (
SELECT
area.a_code,
area.a_description AS Area,
area.a_parent,
district.d_code,
district.d_description AS District,
district.d_parent,
region.r_code,
region.r_description AS Region
FROM region_table region
LEFT JOIN district_table district
ON district.d_parent = region.r_code
LEFT JOIN area_table area
ON area.a_parent = district.d_code
)
SELECT
Region,
District,
Area
FROM final_table