Hi All,can anyone tell me a nice efficient way to do the following..I have 2 tables ([tableA] and [tableB]), tableB has a foreignKey to A and has a running identity column. This means it's easy to identity the most recent piece of data put into it for each instance of A.The following code does this...DECLARE @tableA TABLE ( [Id] INT , [data] VARCHAR(50) )INSERT INTO @tableA SELECT 1,'someDataA'UNION SELECT 2,'someDataB'UNION SELECT 3,'someDataC'DECLARE @tableB TABLE ( [Id] INT IDENTITY(1,1) , [tableAId] INT , [moreData] VARCHAR(50) )-- Data Inserts for AINSERT INTO @tableB SELECT 1, 'firstData A'INSERT INTO @tableB SELECT 1, 'moreData A'INSERT INTO @tableB SELECT 1, 'evenMoredata A'INSERT INTO @tableB SELECT 1, 'lastData A'-- Data Inserts for BINSERT INTO @tableB SELECT 2, 'firstData B'INSERT INTO @tableB SELECT 2, 'lastData B'-- Data Inserts for CINSERT INTO @tableB SELECT 3, 'firstData C'SELECT a.[ID] , a.[data] , b.[moreData]FROM @tablea a JOIN ( SELECT [tableAId] AS tableAId , MAX([Id]) AS tableBId FROM @tableb GROUP BY [tableAId] ) hTableB ON hTableB.[tableAId] = a.[Id] JOIN @tableb b ON b.[Id] = hTableB.[tableBId]
This produces the following results....ID data moreData1 someDataA lastData A2 someDataB lastData B3 someDataC firstData C
What I want is to return the 2nd most recent [Id] for each entry in A.The results I need are theseID data moreData1 someDataA evenMoredata A2 someDataB firstData B3 someDataC (NULL)
Thanks in advance,-------------Charlie