2017-04-24 80 views
-2

我正在嘗試查找多個最大日期。我嘗試了分組,但它只顯示了最大日期。我感謝你的幫助。多個最大值

MemberID Contract Group Date 
1 A 8 11/22/2016 
1 A 61 10/19/2016 
1 A 61 11/19/2015 
1 A 8 7/26/2015 
1 A 8 7/17/2014 
1 A 8 7/17/2013 
1 A 8 5/17/2013 
1 A 8 3/26/2013 

理想的結果將是:

MemberID Contract Group Date 
1 A 8 11/22/2016 
1 A 61 10/19/2016 
1 A 8 7/26/2015 

兩個最大提前日期MEMBERID 1,合同A,集團8

感謝您的幫助。

+0

以及如何日期,我們應該知道*最大*日期你要哪個? – Lamak

+0

你想要最新的2? – Jason

+0

是的,你到底想要什麼?我無法從你指定的內容中知道。爲什麼兩(1,A,8),但只有一個(1,A,61)?你的邏輯是什麼? – pmbAustin

回答

0

我寫這個假設你會比較其他羣體。

DECLARE @priorGroup int = 8; -- Just change these two 
DECLARE @currentGroup int = 61; -- numbers to compare other groups 

WITH max_Dates AS (
SELECT MemberID,[Contract],[Group],MAX([Date]) AS 'Date' 
FROM Table_1 
WHERE [Group] IN (@priorGroup,@currentGroup) 
GROUP BY MemberID,[Contract],[Group]) 

SELECT * 
FROM max_Dates 
WHERE [Group] = @priorGroup 
UNION 
SELECT TOP 1 MemberID,[Contract],[Group],MAX([Date]) AS 'Date' 
FROM Table_1 
WHERE [Group] = @priorGroup 
     AND 
     [Date] < (SELECT [Date] 
       FROM max_Dates 
       WHERE [Group] = @currentGroup) 
GROUP BY MemberID,[Contract],[Group] 

或者你可以嘗試這樣一來對同一行

DECLARE @priorGroup int = 8; 
DECLARE @currentGroup int = 61; 

WITH max_Dates AS (
SELECT MemberID,[Contract],[Group],MAX([Date]) AS 'Date' 
FROM Table_1 
WHERE [Group] IN (@priorGroup,@currentGroup) 
GROUP BY MemberID,[Contract],[Group]) 

SELECT MemberID,[Contract],[Group], 
    (SELECT TOP 1 MAX([Date]) AS 'Date' 
     FROM Table_1 
     WHERE [Group] = @priorGroup 
       AND 
       [Date] < (SELECT [Date] 
         FROM max_Dates 
         WHERE [Group] = @currentGroup) 
         GROUP BY MemberID,[Contract],[Group]) AS 'PriorMax', 
     (SELECT [Date] 
     FROM max_Dates 
     WHERE [Group] = @priorGroup) AS 'Current Max' 
FROM max_Dates 
WHERE [Group] = @priorGroup 
+0

謝謝。我會嘗試。 – Carl

+0

如果您希望在同一行上顯示日期,則添加另一個查詢。 – Jason