我执行了以下查询,其中包含SearchText,SearchURL,LastModifiedDateTime,Country
列 select Top 30 * from SearchHistory order by LastModifiedDateTime desc
这里有很多重复的记录。我需要最新的LastModifiedDatetime记录顺序(SearchURL)。
我尝试了这个查询:
SELECT Top 30 * FROM (SELECT *, Row_number()
OVER(
PARTITION BY SearchURL
ORDER BY LastModifieddateTime desc) AS RN
FROM SearchHistory where searchtext is not null )A
WHERE RN = 1
但我完全得到了不同的结果(非常旧的记录在顶部)。
我需要LastModifiedDatetime desc的前30个不同(searchurl)记录顺序
答案 0 :(得分:1)
答案: 我唯一遗漏的是在RN之后添加order by子句。我认为在searchURL之后ORDER BY LastModifieddateTime desc会照顾它。
SELECT Top 30 * FROM (SELECT *, Row_number()
OVER(
PARTITION BY SearchURL
ORDER BY LastModifieddateTime desc) AS RN
FROM SearchHistory where searchtext is not null )A
WHERE RN = 1 ORDER BY LastModifieddateTime desc
答案 1 :(得分:1)
这是使用分组的更简单的替代方法:
SELECT TOP 30 SearchURL, MAX(LastModifiedDateTime) AS LastModifiedDateTime
FROM SearchHistory
GROUP BY SearchURL
ORDER BY LastModifiedDateTime DESC