SQL查找一个国家/地区的大部分口语

时间:2017-11-13 16:42:56

标签: mysql sql mysql-workbench

我正在尝试根据百分比获得一个国家最多的语言。我正在加入2个表:

Country(NAME,CODE)
CountryLanguage(Percentage, CountryCode, Language)

加入那些2给我

Aruba           Dutch       5.3
Aruba           English     9.5
Aruba           Papiamento  76.7
Aruba           Spanish     7.4
Afghanistan     Balochi     0.9
Afghanistan     Dari        32.1
Afghanistan     Pashto      52.4
Afghanistan     Turkmenian  1.9
Afghanistan     Uzbek       8.8

我试图通过说

获得最多的语言
SELECT co.Name, cl.language, max(cl.Percentage)
from Country co, CountryLanguage cl
where co.Code = cl.CountryCode
group by co.Name

这给了我正确的百分比但错误的语言,我哪里出错?

Afghanistan  Balochi    52.4
Aruba        Dutch      76.7

3 个答案:

答案 0 :(得分:2)

首先,请加入inner join...on

您的查询无效,因为它会获得最大值(百分比),但会显示给定language的任何country

如果我正确理解了您的架构,那么以下查询应该按预期工作:

SELECT co.Name, cl.language, cl.Percentage as percentage
from Country co 
inner join CountryLanguage cl
on co.Code = cl.CountryCode
where (cl.CountryCode,cl.Percentage) in (select CountryCode,max(Percentage)
                                         from CountryLanguage
                                         group by CountryCode)
group by co.Name

答案 1 :(得分:0)

您可以使用窗口函数来获得此答案:

带有RANK

PARTITION可以解决问题

With RecordedPercentages AS
(
              Select 'Aruba' Country, 'Dutch' LanguageName, Cast (5.3 as float) Percentage
    Union All Select 'Aruba', 'English', 9.5
    Union All Select 'Aruba', 'Papiamento', 76.7
    Union All Select 'Aruba', 'Spanish', 7.4
    Union All Select 'Afghanistan', 'Balochi', 0.9
    Union All Select 'Afghanistan', 'Dari', 32.1
    Union All Select 'Afghanistan', 'Pashto', 52.4
    Union All Select 'Afghanistan', 'Turkmenian', 1.9
    Union All Select 'Afghanistan', 'Uzbek', 8.8
),
MyRanking As
(
    Select 
    Country, LanguageName, Percentage, 
    Rank() Over (Partition by Country Order by Percentage Desc) Ranking
    From RecordedPercentages
)
Select *
From MyRanking
Where Ranking = 1

答案 2 :(得分:-1)

只需按两列添加分组

SELECT co.Name, cl.language, max(cl.Percentage)
from Country co, CountryLanguage cl
where co.Code = cl.CountryCode
group by co.Name,cl.language