1

我有下表

Location Type     Date
A        TestType 10-10-2013
A        TestType 05-05-2013
A        BestType 06-06-2013
B        TestType 09-09-2013
B        TestType 01-01-2013

无论类型如何,我都想返回每个位置的最大日期,但我必须返回所有 3 列。

期望的结果:

Location Type     Date
A        TestType 10-10-2013
B        TestType 09-09-2013

最好的方法是什么?

我已经研究过使用RANK() Over Partition,但无法使其正常工作。

4

2 回答 2

5

使用row_number()函数 partition by location ordering by [date] desc 获取 max date每个位置的。

;with cte as (
   select location, type, [date], 
          row_number() over (partition by location order by [date] desc) rn
   from yourTable
)
select location, type, [date]
from cte
where rn = 1 --<<-- rn = 1 gets the max date for each location.

小提琴演示

于 2013-11-04T16:07:25.153 回答
2

你可以做:

SELECT location, MAX(date)
FROM yourTable
GROUP BY location;

编辑:

如果你想用它输入类型,你可以这样做:

select y.location, y.Type, y.date
from YourTable y
inner join(
    select location, max(date) maxdate
    from YourTable
    group by location
) ss on y.location = ss.location and y.date = ss.maxdate

sqlfiddle demo

于 2013-11-04T16:03:48.260 回答