SQL Select 不同的列和最新日期
SQL Select Distinct column and latest date
我正在寻找 select 基于日期的 table 的最新记录,但每个 url 的只有一个不同的列表。 table结构是这样的;
ID URL DateVisited
1 google.com 01-01-2016
2 yahoo.com 01-02-2016
3 google.com 12-30-2015
4 google.com 02-01-2016
所以对于我的结果集,我想要
google.com 02-01-2016
yahoo.com 01-02-2016
我的实际查询中会有更多的条件,但只想获取命中日志中的单个最新记录,而不是不同的 url 和日期的列表,只是不同的 url 和最新日期。
这通常使用 row_number()
:
select t.*
from (select t.*,
row_number() over (partition by url order by datevisited desc) as seqnum
from t
) t
where seqnum = 1;
这允许您获取与最新记录关联的所有列。
使用简单的聚合实际上很容易做到这一点,如下所示:
select URL, max(DateVisited)
from <table>
group by URL
我正在寻找 select 基于日期的 table 的最新记录,但每个 url 的只有一个不同的列表。 table结构是这样的;
ID URL DateVisited
1 google.com 01-01-2016
2 yahoo.com 01-02-2016
3 google.com 12-30-2015
4 google.com 02-01-2016
所以对于我的结果集,我想要
google.com 02-01-2016
yahoo.com 01-02-2016
我的实际查询中会有更多的条件,但只想获取命中日志中的单个最新记录,而不是不同的 url 和日期的列表,只是不同的 url 和最新日期。
这通常使用 row_number()
:
select t.*
from (select t.*,
row_number() over (partition by url order by datevisited desc) as seqnum
from t
) t
where seqnum = 1;
这允许您获取与最新记录关联的所有列。
使用简单的聚合实际上很容易做到这一点,如下所示:
select URL, max(DateVisited)
from <table>
group by URL