Sql按列最高值选择不同的行

时间:2017-11-21 04:26:00

标签: sql

我在尝试为每个城市名称选择一行时遇到问题。这是我得到的以下集合:

enter image description here

这是我目前的查询:

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年。我相信我需要做一个分组或做一个子查询来展平结果。如果有人对如何处理这个问题有任何建议,我们将不胜感激。

2 个答案:

答案 0 :(得分:2)

假设您使用的是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

答案 1 :(得分:1)

以下查询可用于此目的。

CREATE TABLE #TEMP_TEST
(
PlaceId INT,
Name VARCHAR(50),
NumberOfPeople INT,
YEAR INT
)

INSERT INTO #TEMP_TEST 
SELECT 1,'Abbeville',2603,2016
UNION
SELECT 5,'Alabester',32948,2016
UNION
SELECT 9,'Aubum',63118,2016
UNION
SELECT 1,'Abbeville',2402,2015
UNION
SELECT 5,'Alabester',67902,2017



SELECT PlaceId, Name, NumberOfPeople, YEAR  FROM
 (
   SELECT ROW_NUMBER() OVER (PARTITION BY PlaceId ORDER BY YEAR DESC) RNO, 
          PlaceId, Name, NumberOfPeople, YEAR 
   FROM #TEMP_TEST
 )T
WHERE RNO = 1

DROP TABLE  #TEMP_TEST