1

I have a table like:

City date Person A 2018/05/01 peter A 2018/03/01 Jack B 2018/02/16 TOM C 2018/03/01 Mike 

Now I want to find the earliest person for each city. The result will be

A 2018/03/01 Jack B 2018/02/16 TOM C 2018/03/01 Mike 

How to do it?

1

6 Answers 6

5

You could use a subquery with min date for city in join with you table

select m.* from my_table m inner join ( select city, min(date) as min_date from my_table group by city ) t on t.city = m.city and t.min_date = m.date 
Sign up to request clarification or add additional context in comments.

Comments

2

You can use this approach, it will work faster.

select City,[date],Person from CTE a where [date] = (select min([date]) from CTE as b where b.City = a.City); 

2 Comments

Please edit your code to make it appear as code. See here for help on how to do that: stackoverflow.com/editing-help
@rajat, this query will return both records where city = 'A'.
1

You can use TOP 1 WITH TIES

select top 1 with ties City ,date ,Person from MyTable order by row_number() over (partition by City order by date asc) 

SQL Fidddle

Comments

1

Using First_Value () In Sql server

;WITH CTE(City,[date],Person ) AS ( SELECT 'A','2018/05/01','peter' UNION ALL SELECT 'A','2018/03/01','Jack' UNION ALL SELECT 'B','2018/02/16','TOM' UNION ALL SELECT 'C','2018/03/01','Mike' ) SELECT DISTINCT City, FIRST_VALUE([date])OVER (PARTITION BY City ORDER BY [date]) AS [date], FIRST_VALUE(Person)OVER (PARTITION BY City ORDER BY [date])AS Person FROM CTE 

Result,Demo: http://rextester.com/DLPE49383

City date Person -------------------------- A 2018/03/01 Jack B 2018/02/16 TOM C 2018/03/01 Mike 

Comments

0
select City, min(date) as date, Person from T group by City, Person 

1 Comment

grouping by City and Person will not give you the required result. given this data set you'll get the entire table using this.
0

Use ROW_NUMBER

WITH A (City, [Date], Person) AS ( SELECT 'A' , CAST('2018-05-01' AS DATE) , 'Peter' UNION ALL SELECT 'A' , CAST('2018-03-01' AS DATE) , 'Jack' UNION ALL SELECT 'B' , CAST('2018-02-16' AS DATE) , 'TOM' UNION ALL SELECT 'C' , CAST('2018-03-01' AS DATE) , 'Mike' ) SELECT City, [Date], Person FROM ( SELECT ROW_NUMBER () OVER (PARTITION BY City ORDER BY [Date]) Rn , * FROM A ) P WHERE P.RN = 1 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.