I have the following table format:
CREATE TABLE tmp_tbl
(
gcode_id int,
g1code varchar(20),
g2code varchar(20),
g3code varchar(20),
g4code varchar(20)
);
And the following values are inserted:
insert into tmp_tbl values (1, 'AFR', 'AFR-EAST', 'BI', 'BIBJM');
insert into tmp_tbl values (2, 'AFR', 'AFR-SOUTH', 'ZA', 'ZACPT');
insert into tmp_tbl values (3, 'EUR', 'EUR-BRI_IS', 'GB', 'GBMAN');
insert into tmp_tbl values (4, 'EUR', 'EUR-WEST', 'NL', 'NLZWO');
insert into tmp_tbl values (5, 'EUR', 'EUR-WEST', 'BE', 'BELEB');
insert into tmp_tbl values (6, 'EUR', 'EUR-WEST', 'BE', '');
insert into tmp_tbl values (7, 'EUR', 'EUR-WEST', 'NL', '');
insert into tmp_tbl values (8, 'EUR', 'EUR-WEST', '', '');
This is a list of codes where g1code = continent, g2code = region, g3code = country, g4code = city.
The rows with columns that have empty values are to be included if the rest matches.
So if I for example select row 4 then also want row 7 and row 8 to be included. As the empty values can match anything.
I created the following query for this:
SELECT DISTINCT
t1.*,
t2.*,
t3.*,
t4.*
FROM
tmp_tbl tm,
(SELECT * FROM tmp_tbl WHERE g4code = 'NLZWO') g4
OUTER APPLY
(SELECT * FROM tmp_tbl t
WHERE t.g1code = g4.g1code AND t.g2code = '' AND t.g3code = '' AND t.g4code = '') t1
OUTER APPLY
(SELECT * FROM tmp_tbl t
WHERE t.g1code = g4.g1code AND t.g2code = g4.g2code AND t.g3code = '' AND t.g4code = '') t2
OUTER APPLY
(SELECT * FROM tmp_tbl t
WHERE t.g1code = g4.g1code AND t.g2code = g4.g2code AND t.g3code = g4.g3code AND t.g4code = '') t3
OUTER APPLY
(SELECT * FROM tmp_tbl t
WHERE t.g1code = g4.g1code AND t.g2code = g4.g2code AND t.g3code = g4.g3code AND t.g4code = g4.g4code) t4
This does work but I only get 1 row and everything in columns like this:
gcode_id g1code g2code g3code g4code gcode_id g1code g2code g3code g4code gcode_id g1code g2code g3code g4code gcode_id g1code g2code g3code g4code
NULL NULL NULL NULL NULL 8 EUR EUR-WEST 7 EUR EUR-WEST NL 4 EUR EUR-WEST NL NLZWO
Is there a way to do this more efficiently or convert the columns to rows and then end up eventually with id 8, 7 and 4 (where the nulls are filtered out as they are not relevant)?
Thanks