You will need to create 3 queries to do it. But you only need to call the last one to get the result that you are looking for:
First Query qryLastCommentDate
SELECT tblComments.Key, Max(tblComments.Date) AS LastCommentDate
FROM tblComments
GROUP BY tblComments.Key;
Second Query qryNextToLastCommentDate
SELECT tblComments.Key, [qryLastCommentDate].LastCommentDate, Max(tblComments.Date) AS NextToLastCommentDate
FROM tblComments INNER JOIN qryLastCommentDate ON tblComments.Key=[qryLastCommentDate].Key
WHERE (((tblComments.Date)<[LastCommentDate]))
GROUP BY tblComments.Key, [qryLastCommentDate].LastCommentDate;
Third Query qryLastAndNextToLastComments
SELECT tblComments.Key, tblComments.Date, tblComments.Comment
FROM tblComments
WHERE (((tblComments.Key) In (SELECT Key from qryLastCommentDate)) AND ((tblComments.Date) In (SELECT LastCommentDate from qryLastCommentDate))) OR (((tblComments.Key) In (SELECT Key from qryNextToLastCommentDate)) AND ((tblComments.Date) In (SELECT NextToLastCommentDate from qryNextToLastCommentDate)));
Since you are correlating a table to itself, each one needs its own "name". This is the tables alias
Select T.[key], T.[date], T.[comment]
From NPETPROD_TCOMNT as Tthis is the alias for the first instance of the table
Where T.[date]IN
(Select TOP 2 X.[date] From NPETPROD_TCOMNT as X this is the alias for the second instance of the table
Where X.[key]= T.[key]here is where the two tables are correlated so you get the correct date for each id
Order By X.[date] DESC)
The above SQL can conceivably generate more than two records for each key value if there are multiple entries for a date. For example
[tt]
Key Date Comment
1 01/05/04 Jan 5 Comment
1 01/15/04 Jan 15 Comment 1
1 01/15/04 Jan 15 Comment 2
[/tt]
Would return all three records because there are two 01/15/04 records and there's no way to decide which to return.
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.