问题
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