Shawn
Shawn

Reputation: 2435

Sql select distinct row by a columns highest value

I am having an issue trying to select one row per city name. This is the following collection I am getting:

enter image description here

This is my query so far:

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

I am trying to get it to where it only selects a city one time, but uses the most recent date. So in the above picture, I would only see Abbeville for 2016 and not 2015. I believe I need to do either a group by or do a sub query to flatten the results. If anybody has any advice on how I can handle this, it will be greatly appreciated.

Upvotes: 0

Views: 36

Answers (2)

Aswani Madhavan
Aswani Madhavan

Reputation: 816

The following query serves the purpose.

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

Upvotes: 1

TheGameiswar
TheGameiswar

Reputation: 28890

Assuming you are using SQLSERVER,you can use 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

Upvotes: 2

Related Questions