如何从组中选择按日期排序的第一行

时间:2018-05-16 08:32:57

标签: sql sql-server

我有一张表:

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

现在我想找到每个城市最早的人。 结果将是

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

怎么做?

6 个答案:

答案 0 :(得分:3)

你可以使用一个子查询,其中城市的最小日期与你的表连接

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 

答案 1 :(得分:1)

您可以使用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

答案 2 :(得分:1)

你可以使用这种方法,它会更快地运作。

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

答案 3 :(得分:1)

在Sql server中使用First_Value()

;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

结果,演示:http://rextester.com/DLPE49383

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

答案 4 :(得分:0)

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

答案 5 :(得分:0)

使用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