SQL MAX日期没有group by

时间:2013-11-04 16:01:51

标签: sql sql-server sql-server-2008 sql-server-2008-r2

我有下表

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,但无法让它正常工作。

2 个答案:

答案 0 :(得分: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.

<强> Fiddle demo

答案 1 :(得分: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