没有分组依据的 SQL MAX 日期 [英] SQL MAX date without group by
本文介绍了没有分组依据的 SQL MAX 日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有下表
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 列.
I want to return the max date for each location regardless of the type but I must return all 3 columns.
想要的结果:
Location Type Date
A TestType 10-10-2013
B TestType 09-09-2013
最好的方法是什么?
我曾考虑使用 RANK() Over Partition
,但无法使其正常工作.
I've looked into using RANK() Over Partition
, but can't get it to work properly.
推荐答案
使用 row_number()
函数 and 按位置按 [date] desc 排序
获取每个位置的 最大日期
.
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.
这篇关于没有分组依据的 SQL MAX 日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文