我在尝试为每个城市名称选择一行时遇到问题。这是我得到的以下集合:
到目前为止,这是我的查询:
select pl.PlaceId,
pl.Name,
pop.NumberOfPeople,
pop.Year
from dbo.Places pl
inner join dbo.Populations pop
on pop.PlaceId = pl.PlaceId
where pop.NumberOfPeople >= 1000
and pop.NumberOfPeople <= 99999
我试图让它只选择一次城市,但使用最近的日期。所以在上图中,我只会看到 2016 年的 Abbeville 而不是 2015 年。我相信我需要执行 group by 或执行子查询来展平结果。如果有人对我如何处理这个问题有任何建议,将不胜感激。
假设您使用的是 SQLSERVER,则可以使用 Rownumber
;with cte
as
(select pl.PlaceId,
pl.Name,
pop.NumberOfPeople,
pop.Year,
row_number() over(partition by pl.Name order by year desc) as rownum
from dbo.Places pl
inner join dbo.Populations pop
on pop.PlaceId = pl.PlaceId
where pop.NumberOfPeople >= 1000
and pop.NumberOfPeople <= 99999
)
select * from cte where rownum=1
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句