Home Forums SQL Server 2008 T-SQL (SS2K8) Delete other than top 2 rows for each foreign key element in table. RE: Delete other than top 2 rows for each foreign key element in table.

  • Sample data, in case anyone else wants to have a go: -

    SELECT [MemberId(F.K)], [Event], [Event Date]

    INTO #yourTable

    FROM (VALUES(1, 'Test Event1', '2012-03-20 05:39:51'),

    (1, 'Test Event1', '2012-03-21 05:39:51'),

    (1, 'Test Event1', '2012-03-22 05:39:51'),

    (3, 'Test Event3', '2012-03-23 05:39:51'),

    (2, 'Test Event2', '2012-03-24 05:39:51'),

    (2, 'Test Event2', '2012-03-19 05:39:51'),

    (1, 'Test Event1', '2012-03-23 05:49:51'),

    (3, 'Test Event3', '2012-03-23 05:49:51'),

    (4, 'Test Event4', '2012-03-27 05:39:51'),

    (3, 'Test Event3', '2012-03-21 05:39:51')

    )a([MemberId(F.K)], [Event], [Event Date]);

    Solution: -

    SELECT [MemberId(F.K)], [Event], [Event Date]

    FROM #yourTable a

    WHERE [Event Date] IN (SELECT TOP 2 [Event Date]

    FROM #yourTable b

    WHERE a.[MemberId(F.K)] = b.[MemberId(F.K)] AND a.[Event Date] <= b.[Event Date]

    ORDER BY [Event Date] DESC

    );

    Be aware that this is infinitely worse than using the ROW_NUMBER function.


    Forever trying to learn
    My blog - http://www.cadavre.co.uk/
    For better, quicker answers on T-SQL questions, click on the following...http://www.sqlservercentral.com/articles/Best+Practices/61537/
    For better, quicker answers on SQL Server performance related questions, click on the following...http://www.sqlservercentral.com/articles/SQLServerCentral/66909/