我寫這個假設你會比較其他羣體。
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
以及如何日期,我們應該知道*最大*日期你要哪個? – Lamak
你想要最新的2? – Jason
是的,你到底想要什麼?我無法從你指定的內容中知道。爲什麼兩(1,A,8),但只有一個(1,A,61)?你的邏輯是什麼? – pmbAustin