MySQL将表转换为不带空值的矩阵

MySQL将表转换为不带空值的矩阵,mysql,sql,matrix,pivot-table,Mysql,Sql,Matrix,Pivot Table,我有一个表格,上面有不同语言的国家和翻译,类似这样(可能有些数据可能是错误的,但只是样本值): 我需要得到的是一个矩阵,显示语言的一列,类似于: countryId, countryName, es, fr, 1, spain, españa, espagne 2, france, francia, france 3, italy, italia, italie 我试过使用CASE语句: SELECT co

我有一个表格,上面有不同语言的国家和翻译,类似这样(可能有些数据可能是错误的,但只是样本值):

我需要得到的是一个矩阵,显示语言的一列,类似于:

countryId, countryName, es,     fr,
1,           spain,    españa,  espagne
2,           france,   francia, france
3,           italy,    italia,  italie
我试过使用CASE语句:

SELECT countryId, 
case WHEN idLan =1 THEN translation  end as en,
case WHEN idLan =2 THEN translation END as es, 
case WHEN idLan =3 THEN translation END as fr,
FROM translations
但我在每一列中都有很多空值,如下所示:

countryId, en,    es,     fr
1,       spain,  NULL,    NULL
2,       france, NULL,    NULL
3,       Italy,  NULL,    NULL
1,       NULL,   españa,  NULL
2,       NULL,   francia, NULL
3,       NULL,   italia,  NULL...
如何得到这样的矩阵,但要避免空值

countryId, en,    es,       fr
1,       spain,  españa,   espagne
2,       france, francia,  france
3,       Italy,  italia,   italie

坦克。

您需要根据countryId进行分组:

SELECT countryId, 
case WHEN lanId = 1 THEN translation END as en,
case WHEN lanId = 2 THEN translation END as es, 
case WHEN lanId = 3 THEN translation END as fr
FROM translations
GROUP BY countryId

您需要按countryId进行分组:

SELECT countryId, 
case WHEN lanId = 1 THEN translation END as en,
case WHEN lanId = 2 THEN translation END as es, 
case WHEN lanId = 3 THEN translation END as fr
FROM translations
GROUP BY countryId

尝试以下pivot查询:

SELECT
    countryId,
    name,
    MAX(CASE WHEN lanId = 1 THEN translation END) AS en,
    MAX(CASE WHEN lanId = 2 THEN translation END) AS es,
    MAX(CASE WHEN lanId = 3 THEN translation END) AS fr
FROM translations
GROUP BY
    countryId,
    name
输出:

此处演示:


尝试以下透视查询:

SELECT
    countryId,
    name,
    MAX(CASE WHEN lanId = 1 THEN translation END) AS en,
    MAX(CASE WHEN lanId = 2 THEN translation END) AS es,
    MAX(CASE WHEN lanId = 3 THEN translation END) AS fr
FROM translations
GROUP BY
    countryId,
    name
输出:

此处演示:


您也需要一个小组。谢谢。关键是按countryId和名称分组。您也需要按分组。谢谢。密钥是按countryId和名称分组的。