仅检索具有MAX DateCreated的记录

时间:2015-04-21 16:39:00

标签: sql sql-server sql-server-2008 max

我有一个返回多条记录的大型查询。我只需要从中创建具有最新创建日期的记录。我尝试过使用子查询和ROW_NUMBER()OVER(PARTITION BY,无法解决这个问题。

例如,如果我的查询返回100条记录,而其中只有5条记录具有最新日期,那么我的最终查询应该只返回这5条记录。

SELECT ROW_NUMBER() OVER (PARTITION BY c.CustomerName, c.DateCreated ORDER BY c.DateCreated Desc, COUNT(*) Desc) AS rn, DateCreated
FROM  Customer As c   
WHERE c.Field1 = @Param1 and c.Field2= @Param2

在这种情况下,我通常会做WHERE rn = 1 ....但是我的结果对每个不同的DateCreated都有分组,所以'rn'列就像1,2,3,1,2,3,1 -1,2,3,4-

2 个答案:

答案 0 :(得分:1)

从分区中删除日期。您想在一个客户中工作并选择最新日期。我也不确切知道,但考虑从count(*)子句中删除order by

SELECT ROW_NUMBER() OVER (PARTITION BY c.CustomerName ORDER BY c.DateCreated Desc, COUNT(*) Desc) AS rn, DateCreated
FROM  Customer As c   
WHERE c.Field1 = @Param1 and c.Field2= @Param2

答案 1 :(得分:1)

从分区中删除日期;它会为您描述的每个客户/日期组合返回一行。试试这个:

WITH cte AS (
SELECT 
    ROW_NUMBER() OVER (PARTITION BY c.CustomerName ORDER BY c.DateCreated Desc) AS rn, 
    DateCreated
FROM  Customer As c   
WHERE c.Field1 = @Param1 and c.Field2= @Param2
)

SELECT
*
FROM cte 
WHERE rn = 1