Puoi farlo con substring_index()
. La query seguente usa la tua come sottoquery e quindi applica questa logica:
select Name, ISOCode_2,
substring_index(currencies, ',', 1) as Currency1,
(case when numc >= 2 then substring_index(substring_index(currencies, ',', 2), ',', -1) end) as Currency2,
(case when numc >= 3 then substring_index(substring_index(currencies, ',', 3), ',', -1) end) as Currency3,
(case when numc >= 4 then substring_index(substring_index(currencies, ',', 4), ',', -1) end) as Currency4,
(case when numc >= 5 then substring_index(substring_index(currencies, ',', 5), ',', -1) end) as Currency5,
(case when numc >= 6 then substring_index(substring_index(currencies, ',', 6), ',', -1) end) as Currency6,
(case when numc >= 7 then substring_index(substring_index(currencies, ',', 7), ',', -1) end) as Currency7,
(case when numc >= 8 then substring_index(substring_index(currencies, ',', 8), ',', -1) end) as Currency8
from (SELECT country.Name, country.ISOCode_2, group_concat(currency.name) AS currencies,
count(*) as numc
FROM country
INNER JOIN countryCurrency ON country.country_id = countryCurrency.country_id
INNER JOIN currency ON currency.currency_id = countryCurrency.currency_id
GROUP BY country.name
) t
L'espressione substring_index(currencies, ',' 2)
porta la lista in valute fino alla seconda. Per la Somoa americana, sarebbe 'US Dollar,Kwanza'
. La prossima chiamata con -1
poiché l'argomento prende l'ultimo elemento della lista, che sarebbe 'Kwanza'
, che è il secondo elemento di currencies
.
Si noti inoltre che le query SQL restituiscono un insieme ben definito di colonne. Una query non può avere un numero variabile di colonne (a meno che tu non stia utilizzando SQL dinamico tramite un prepare
dichiarazione).