Home Forums SQL Server 2012 SQL Server 2012 - T-SQL Finding the most recent value for many record in a detail table (optimizing) RE: Finding the most recent value for many record in a detail table (optimizing)

  • Bhaskar.Shetty (5/24/2013)


    How about this solutions...

    --- Create a InLine Function with ReportingDate Parameter --

    CREATE FUNCTION fnMostRecentOrderDetail(@ReportingDate datetime) RETURNS TABLE

    AS

    RETURN

    (

    SELECT ProductId, SalesOrderDetailId, ModifiedDate,

    ROW_NUMBER() OVER (PARTITION BY ProductId ORDER BY ModifiedDate DESC) RowNo

    FROM sales.SalesOrderDetail

    WHERE ModifiedDate < @ReportingDate

    )

    GO

    and then...

    -- Join the function with ReportingDate Parameter --

    declare @ReportingDate DATE = '9/7/2007'

    SELECT

    Name

    ,ReportDate = @ReportingDate

    ,MostRecent.ModifiedDate

    FROM Production.Product Product

    LEFT OUTER JOIN fnMostRecentOrderDetail(@ReportingDate) MostRecent ON Product.ProductID = MostRecent.ProductId and RowNo = 1

    I have a solution very similar now.

    Currently it's a inline table function that takes a product id and date, then returns the one reference back to the record.

    It uses the Row_Number() ORDER BY... where RowNumber = 1, but inside of the function, so it always just returns a single row.

    Currently it's not in the AdventureWorks db, it's in my actual db. But I'm interested in this sort of thing, so I'll probobly post up here the three different methods I'm seeing and the differences. AdventureWorks might be too small to really differentiate the performance, but we'll see.

    We have the Top 1 Desc (starting), Return Row_Number 1 for a very specific item (my new) and Return Row_Numbers and join on 1 to limit the results (actually returns multiple) that you gave me.