gpt4 book ai didi

MySQL 将表转换为没有空值的矩阵

转载 作者:行者123 更新时间:2023-11-29 07:00:35 26 4
gpt4 key购买 nike

我有一个包含国家/地区和不同语言翻译的表格,如下所示(也许某些数据可能是错误的,但只是示例值):

lanId, countryId, name, translation
1, 1, Spain, Spain
1, 2, France, France
1, 3, Italy, Italy
2, 1, Spain, España
2, 2, France, Francia
2, 3, Italy, Italia
3, 1, Spain, Espagne
3, 2, France, France
3, 3, Italy, Italie

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

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

但是我在每一列中都得到很多 NULL,如下所示:

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

坦克。

最佳答案

尝试以下数据透视查询:

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

输出:

enter image description here

此处演示:

Rextester

关于MySQL 将表转换为没有空值的矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43629484/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com