2014-04-15 83 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