Select 每个城市工资最高的人
Select person with the highest salary in every city
使用此模型描述的数据库,我需要用以下列显示 table:
cities.name | persons.first_name+'space'+persons.last_name AS [THE LUCKY
MAN] | occupations.salary [the best salary]
这是一个棘手的问题,因为实体 "Cities" 和 "Occupations" 之间没有直接联系。
@UPDATE
不,这不是作业。我能给出的最接近的答案:
SELECT cP.name, p.first_name+' '+p.last_name AS [The lucky man], T.[MAX] FROM cities cP
JOIN persons p ON (p.id_city=cP.id_city)
JOIN occupations o ON (p.id_persons=o.id_person)
JOIN (SELECT MAX(ow.salary) AS [MAX], ow.id_person AS [idperson] FROM occupations ow GROUP BY ow.id_person) T ON (p.id_persons=T.[idperson])
也许这个问题只是令人困惑而不是棘手。
编辑 - 感谢您发布您目前所做的一切。问题是,在选择最大值时,您也会按人分组。仅按城市分组时必须选择最大值,然后必须将这些值(城市和最高薪水)连接回原始表。
附带说明一下,在下面的查询中,如果您想显示没有人的城市(从技术上讲,最高薪水为零),内联 view/subquery 中的联接应该是外部联接。 =11=]
select c.name,
p.first_name+'space'+p.last_name AS [THE LUCKY MAN],
o.salary [the best salary]
from persons p
join cities c
on p.id_city = c.id_sity
join occupations o
on p.id_person = o.id_person
join ( select p.id_city,
max(o.salary) as city_highest
from persons p
join occupations o
on p.id_person = o.id_person
group by p.id_city
) v
on p.id_city = v.id_city
and o.salary = v.city_highest
使用此模型描述的数据库,我需要用以下列显示 table:
cities.name | persons.first_name+'space'+persons.last_name AS [THE LUCKY MAN] | occupations.salary [the best salary]
这是一个棘手的问题,因为实体 "Cities" 和 "Occupations" 之间没有直接联系。
@UPDATE
不,这不是作业。我能给出的最接近的答案:
SELECT cP.name, p.first_name+' '+p.last_name AS [The lucky man], T.[MAX] FROM cities cP
JOIN persons p ON (p.id_city=cP.id_city)
JOIN occupations o ON (p.id_persons=o.id_person)
JOIN (SELECT MAX(ow.salary) AS [MAX], ow.id_person AS [idperson] FROM occupations ow GROUP BY ow.id_person) T ON (p.id_persons=T.[idperson])
也许这个问题只是令人困惑而不是棘手。
编辑 - 感谢您发布您目前所做的一切。问题是,在选择最大值时,您也会按人分组。仅按城市分组时必须选择最大值,然后必须将这些值(城市和最高薪水)连接回原始表。
附带说明一下,在下面的查询中,如果您想显示没有人的城市(从技术上讲,最高薪水为零),内联 view/subquery 中的联接应该是外部联接。 =11=]
select c.name,
p.first_name+'space'+p.last_name AS [THE LUCKY MAN],
o.salary [the best salary]
from persons p
join cities c
on p.id_city = c.id_sity
join occupations o
on p.id_person = o.id_person
join ( select p.id_city,
max(o.salary) as city_highest
from persons p
join occupations o
on p.id_person = o.id_person
group by p.id_city
) v
on p.id_city = v.id_city
and o.salary = v.city_highest