• It's alright to be grumpy, just remember we're all volunteers too, and we're trying to make sure we don't waste your time either. A few clarifications cleans up a few dozen assumptions that can lead to blind alleys.

    So, here's the basic plan when you're going into a logging table to find the most recent entries for a date. Find the max date in the table below your date for the key, then rejoin on the key. There are multiple approaches to this method, below is one of them:

    IF OBJECT_ID( 'tempdb..#foo') IS NOT NULL

    DROP TABLE #foo

    Create table #foo (item char(1), changedate datetime, value int)

    insert #foo (item, changedate, value)

    values ('x', '2014-06-15', 0)

    insert #foo (item, changedate, value)

    values ('y', '2014-06-16', 1)

    insert #foo (item, changedate, value)

    values ('x', '2014-07-10', 1)

    insert #foo (item, changedate, value)

    values ('y', '2014-07-15', 2)

    DECLARE @DateToGet DATETIME

    SET @DateToGet = '20140709'

    SELECt

    *

    FROM

    #foo AS f

    JOIN

    (SELECT

    item, MAX(changeDate) AS MaxCD

    FROM

    #foo

    WHERE

    ChangeDate <= @DateToGet

    GROUP BY

    item

    ) AS drv

    ONf.item = drv.item

    and f.ChangeDate = drv.MaxCD

    If you need to do this for a range, use another table to contain your range, feed its date column in as a replacement for the @DateToGet variable.


    - Craig Farrell

    Never stop learning, even if it hurts. Ego bruises are practically mandatory as you learn unless you've never risked enough to make a mistake.

    For better assistance in answering your questions[/url] | Forum Netiquette
    For index/tuning help, follow these directions.[/url] |Tally Tables[/url]

    Twitter: @AnyWayDBA