为什么Max函数返回值为0的行

问题描述 投票:0回答:2

任何人都可以告诉我为什么以下查询似乎返回百分比值为0的行存在。

SELECT cl.countrycode, c.name, c.continent, cl.language
FROM country c
JOIN countrylanguage cl ON cl.countrycode = c.code
WHERE Percentage = ANY (SELECT MAX(Percentage) FROM countrylanguage GROUP BY countrycode)

我可以在查询中添加'&& percentage> 0'来过滤掉这些,但MAX函数应该只过滤每个国家代码的最大百分比?

sql max where
2个回答
0
投票

尝试像这样修改;

SELECT cl.countrycode, c.name, c.continent, cl.language
FROM country c
JOIN countrylanguage cl ON cl.countrycode = c.code
WHERE Percentage = (SELECT MAX(Percentage) FROM countrylanguage cl2 where cl2.countrycode=cl.countrycode)

0
投票

这是您的查询:

SELECT cl.countrycode, c.name, c.continent, cl.language
FROM country c JOIN
     countrylanguage cl
     ON cl.countrycode = c.code
WHERE Percentage = ANY (SELECT MAX(Percentage)
                        FROM countrylanguage
                        GROUP BY countrycode
                       );

子查询返回所有国家/地区的最大值百分比。有些国家可能会有一排0是最大值。您可以单独运行查询以查看此信息。

然后外部查询找到与任何国家/地区的最大值匹配的任何百分比。这真的没有意义。

你想要的是每个国家的最大值。为此,使用相关子查询:

SELECT cl.countrycode, c.name, c.continent, cl.language
FROM country c JOIN
     countrylanguage cl
     ON cl.countrycode = c.code
WHERE cl.Percentage = (SELECT MAX(cl2.Percentage)
                       FROM countrylanguage cl2
                       WHERE cl2.countrycode = cl.countrycode
                      );

区别在于子查询现在有一个WHERE条款而不是GROUP BY条款,强制要求各国相同。

© www.soinside.com 2019 - 2024. All rights reserved.