簡體   English   中英

SQL GROUP_CONCAT分成不同的列

[英]SQL GROUP_CONCAT split in different columns

我搜索了很多,但沒有找到解決問題的正確方法。

我想做什么?

我在MySQL中有兩個表: - 國家 - 貨幣(我通過CountryCurrency將它們連接起來 - >由於多對多關系)

請參閱此示例以獲取一個工作示例: http//sqlfiddle.com/#!2/317d3/8/0

我想使用連接將兩個表鏈接在一起,但我希望每個國家只顯示一行(某些國家/地區有多種貨幣,因此這是第一個問題)。

我找到了group_concat函數:

SELECT country.Name, country.ISOCode_2, group_concat(currency.name) AS currency
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

這有以下結果:

NAME            ISOCODE_2   CURRENCY

Afghanistan AF          Afghani
Åland Islands   AX          Euro
Albania         AL          Lek
Algeria         DZ          Algerian Dinar
American Samoa  AS          US Dollar,Kwanza,East Caribbean Dollar

但我現在想要的是將貨幣分成不同的列(貨幣1,貨幣2,......)。 我已經嘗試過像MAKE_SET()這樣的函數,但這不起作用。

你可以用substring_index()來做到這一點。 以下查詢將您的子查詢用作子查詢,然后應用此邏輯:

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

表達式substring_index(currencies, ',' 2)將貨幣列表中的貨幣列為第二個貨幣。 對於美國的Somoa來說,那將是'US Dollar,Kwanza' -1作為參數的下一個調用采用列表的最后一個元素,即'Kwanza' ,這是currencies的第二個元素。

另請注意,SQL查詢返回一組明確定義的列。 查詢不能具有可變數量的列(除非您通過prepare語句使用動態SQL)。

使用此查詢計算出您需要的貨幣列數:

SELECT MAX(c) FROM 
((SELECT count(currency.name) AS c
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) as t)

然后動態創建並執行預准備語句以生成結果,使用帶有上述查詢結果的Gordon Linoff解決方案在此線程中。

Ypu可以使用動態SQL,但您必須使用過程

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM