SQL MAX date without group by

社会主义新天地 提交于 2019-12-24 09:49:05

问题


I have the following table

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

I want to return the max date for each location regardless of the type but I must return all 3 columns.

Desired result:

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

What would be the best way to do this?

I've looked into using RANK() Over Partition, but can't get it to work properly.


回答1:


Using row_number() function and partition by location ordering by [date] desc to get the max date for each location.

;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




回答2:


You can do:

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

EDIT:

If you want to get type with it you can do:

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



来源:https://stackoverflow.com/questions/19771780/sql-max-date-without-group-by

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!