我有以下表
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
,但不能让它正常工作。
使用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.
小提琴演示
你可以做:
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演示