我有这种关系; 国家(名称,代码,资本,省,地区,人口)
我希望从哪里获得语言(名称),以每种语言的母语人口数量说出他们所使用的国家/地区的数量。
我很确定我差不多完成了这个,但我认为我并没有真正使用“ORDER BY”的内容,因为我对count(l.name)的计算得到了当我确定该数据库包含某些国家/地区使用某种语言的信息时,凌乱且只能获得值“1”!
SELECT DISTINCT l.name, count(l.name) as SpokenIn,
l.percentage*c.population as NativeSpeakers
FROM (country c
JOIN language l
ON c.code = l.country)
GROUP BY l.name, NativeSpeakers;
所有其他行都很好,只有“SpokenIn”关系很乱。我做错了什么:(
我正在使用PostgreSQL。
答案 0 :(得分:1)
尝试:
select l.name,
counter.num_countries as SpokenIn,
sum(l.percentage * c.population) as NativeSpeakers
from country c
join language l
on c.code = l.country
join (select name, count(country) as num_countries
from language
group by name) counter
on l.name = counter.name
group by l.name, counter.num_countries
修改 - 修复拼写错误“县”与国家
答案 1 :(得分:0)
我不是PostgreSQL专家,但我认为你犯了一个小错误。您正在对NativeSpeakers列进行分组,但实际上您需要所有原生音色的总和。请尝试以下方法:
SELECT l.name, count(c.name) as SpokenIn,
sum(l.percentage*c.population) as NativeSpeakers
FROM (country c
JOIN language l
ON c.code = l.country)
GROUP BY l.name;
如果你想用它来捣乱一些: http://www.sqlfiddle.com/#!15/0d0bc/3
答案 2 :(得分:0)
您是否只想弄清楚每种语言的人数?如果是这样,这可能是构建查询的更好方法:
SELECT DISTINCT l.name, sum(l.percentage*c.population) as SpokenBy
FROM (country c
JOIN language l
ON c.code = l.country)
GROUP BY l.Name