0

It's done with the use of ID but I want without using ID

 SELECT
        ID
        ,COALESCE(p.number, 
            (SELECT TOP (1) number 
            FROM tablea AS p2 
            WHERE
                p2.number IS NOT NULL 
                AND p2.ID <= p.ID ORDER BY p2.ID DESC))as Number--,Result = p.number
    FROM TableA AS p;

ID  number
1   100
2   150
3   NULL
4   300
5   NULL
6   NULL
7   450
8   NULL
9   NULL
10  560
11  NULL
12  880
13  NULL
14  579
15  987
16  NULL
17  NULL
18  NULL
2
  • ID is used to define the order of rows. If you have other columns that define the order, use them. If you don't have such a column - add it. Somehow you need to tell the server what does "previous" row mean. Commented Mar 31, 2016 at 11:59
  • We can do with ROW_NUMBER()..But I don't know how to use it Commented Apr 1, 2016 at 5:05

1 Answer 1

1

Try this query. This will help you get your desired result set. This query is written in SQL Server 2008 R2.

WITH CTE AS
( SELECT id, number FROM tablea)
SELECT A.id, A.number, ISNULL(A.number,B.number) number
FROM CTE A
OUTER APPLY (SELECT TOP 1 *
FROM CTE 
WHERE id < a.id AND number IS NOT NULL
ORDER BY id DESC) B

You can try using LAG and LEAD functions in SQL Server 2012/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.