So we have to work on the following tables-
To find the furthest continent for each client, our condition is America is the closest continent and Asia is the furthest continent after Europe. Try the following SQL code-
WITH Client_Continents AS (
SELECT
cn.Client,
c.Continent,
CASE
WHEN c.Continent = 'America' THEN 1
WHEN c.Continent = 'Europe' THEN 2
WHEN c.Continent = 'Asia' THEN 3
ELSE 0
END AS ContinentScore
FROM Client_Nationality cn
LEFT JOIN Continent c ON cn.First_Nationality = c.Country_Code
UNION ALL
SELECT
cn.Client,
c.Continent,
CASE
WHEN c.Continent = 'America' THEN 1
WHEN c.Continent = 'Europe' THEN 2
WHEN c.Continent = 'Asia' THEN 3
ELSE 0
END AS ContinentScore
FROM Client_Nationality cn
LEFT JOIN Continent c ON cn.Second_Nationality = c.Country_Code
UNION ALL
SELECT
cn.Client,
c.Continent,
CASE
WHEN c.Continent = 'America' THEN 1
WHEN c.Continent = 'Europe' THEN 2
WHEN c.Continent = 'Asia' THEN 3
ELSE 0
END AS ContinentScore
FROM Client_Nationality cn
LEFT JOIN Continent c ON cn.third_Nationality = c.Country_Code
),
Max_Continent AS (
SELECT
Client,
MAX(ContinentScore) AS MaxContinentScore
FROM Client_Continents
GROUP BY Client
)
SELECT
cc.Continent,
COUNT(DISTINCT cc.Client) AS ClientCount
FROM Client_Continents cc
JOIN Max_Continent mc ON cc.Client = mc.Client
WHERE cc.ContinentScore = mc.MaxContinentScore
GROUP BY cc.Continent
ORDER BY ClientCount;
Provides the result set -
