2014-04-15 41 views
0
client_ref matter_suffix date_opened 
1   1    1983-11-15 00:00:00.000 
1   1    1983-11-15 00:00:00.000 
1   6    2002-11-18 00:00:00.000 
1   7    2005-08-01 00:00:00.000 
1   9    2008-07-01 00:00:00.000 
1   10    2008-08-22 00:00:00.000 
2   1    1983-11-15 00:00:00.000 
2   2    1992-04-21 00:00:00.000 
3   1    1983-11-15 00:00:00.000 
3   2    1987-02-26 00:00:00.000 
4   1    1989-01-07 00:00:00.000 
4   2    1987-03-15 00:00:00.000 

我上面的表,我只是想返回打开每个客户端的最近的事情,在下面的格式:从聚合函数结果等栏目包括数据

client_ref matter_suffix Most Recent 
1   10     2008-08-22 00:00:00.000 
2   2     1992-04-21 00:00:00.000 
3   2     1987-02-26 00:00:00.000 
4   1     1989-01-07 00:00:00.000 

我可以执行一个非常简单的查询来返回最近的(如下所示),但每当我尝试包含matter_suffix数据(必要)时,我都会遇到问题。

在此先感谢。

select client_ref,max (Date_opened)[Most Recent] from archive a 
group by client_ref 
order by client_ref 

回答

0

在SQL 2012有方便的功能,使它更容易些,但在2008年SQL你需要做旧的方式:

找到最新:

SELECT client_ref,MAX(date_opened) last_opened 
FROM YourTable 
GROUP BY client_ref 

现在加入到背:

SELECT client_ref,matter_suffix, date_opened 
FROM YourTable YT 
INNER JOIN 
(
SELECT client_ref,MAX(date_opened) last_opened 
FROM YourTable 
GROUP BY client_ref 
) MR 
ON YT.client_ref = MR.client_ref 
AND YT.date_opened = MR.last_opened 
+0

好极了,这已经返回那里有超过1开上了最多个值的好处最近的日期(我没有在截断的示例表中显示)。谢谢大家! – BenjKenj

+0

很高兴它有用。你可能想比较GarethD的表现。 –

0

这不工作?

select client_ref,matter_suffix,max (Date_opened)[Most Recent] from archive a 
group by client_ref,matter_suffix 
order by client_ref 
0

可以使用ROW_NUMBER功能,让每client_ref的最新记录:

SELECT client_ref, matter_suffix, Date_opened 
FROM ( SELECT client_ref, 
        matter_suffix, 
        Date_opened, 
        RowNumber = ROW_NUMBER() OVER(PARTITION BY client_ref 
                ORDER BY Date_opened DESC) 
      FROM archive a 
     ) a 
WHERE RowNumber = 1; 

如果您想返回所有行有一个以上的行具有相同的最大敞开日期,那么你可以使用RANK:

SELECT client_ref, matter_suffix, Date_opened 
FROM ( SELECT client_ref, 
        matter_suffix, 
        Date_opened, 
        RowNumber = RANK() OVER(PARTITION BY client_ref 
                ORDER BY Date_opened DESC) 
      FROM archive a 
     ) a 
WHERE RowNumber = 1; 
0
select client_ref,max (matter_suffix),RN = ROW_NUMBER()OVER(PARTITION BY matter_suffix ORDER BY Date_opened desc) from archive a 
WHERE RN = 1 
group by client_ref,Date_opened 
order by client_ref,Date_opened 
+0

您可以通过解释您通过链接到有用文档所做的代码更改来改进此答案,并阅读所采用的方法。 – StuperUser