get previous value

  • Hi,

    I am having the below records

    Date value

    01-01-2013 10

    02-01-2013 20

    03-01-2013 0

    04-01-2013 0

    05-01-2013 30

    06-01-2013 40

    07-01-2013 0

    08-01-2013 50

    I want to display the value 20 for the dates 3rd and 4th and value 40 for the date 07th.

    In general, for any date if the value is 0 then get the privoud non zero value.

    Can anyone pls help me to get this one

    Thanks

    Naveen

  • ;WITH SampleData (Date, value) AS (

    SELECT '01-01-2013', 10 UNION ALL

    SELECT '02-01-2013', 20 UNION ALL

    SELECT '03-01-2013', 0 UNION ALL

    SELECT '04-01-2013', 0 UNION ALL

    SELECT '05-01-2013', 30 UNION ALL

    SELECT '06-01-2013', 40 UNION ALL

    SELECT '07-01-2013', 0 UNION ALL

    SELECT '08-01-2013', 50

    )

    SELECT s.[Date], value = ISNULL(NULLIF(s.value,0), x.value)

    FROM SampleData s

    CROSS APPLY (

    SELECT TOP 1 si.value

    FROM SampleData si

    WHERE si.[Date] <= s.[Date]

    AND si.value > 0

    ORDER BY si.[Date] DESC

    ) x

    ORDER BY s.[Date]

    “Write the query the simplest way. If through testing it becomes clear that the performance is inadequate, consider alternative query forms.” - Gail Shaw

    For fast, accurate and documented assistance in answering your questions, please read this article.
    Understanding and using APPLY, (I) and (II) Paul White
    Hidden RBAR: Triangular Joins / The "Numbers" or "Tally" Table: What it is and how it replaces a loop Jeff Moden

Viewing 2 posts - 1 through 1 (of 1 total)

You must be logged in to reply to this topic. Login to reply