[英]SQL MAX date without group by
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. 无论类型如何,我都想返回每个位置的最长日期,但是我必须返回所有3列。
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. 我已经研究
RANK() Over Partition
使用RANK() Over Partition
,但无法使其正常工作。
Using row_number()
function and partition by location ordering by [date] desc
to get the max date
for each location. 使用
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.
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.