0

I'd like to replace NULL value for each code group using the value before the first Null:

code     amount       date
-------------------------------
 A        1500     2013-02-03
 A        1800     2013-03-05
 A        1300        NULL
 A        1300        NULL
 B        1300     2013-05-03
 B        1300     2013-06-01
 B        1300     2013-07-02
 B        1600        NULL
 B        1300        NULL
 C        1200     2014-07-02
 C        1500     2014-08-05
 C        1700        NULL
 C        1100        NULL
 C        1300        NULL

In this table, I want to replace NULL value for the date for each "code" with last date value for that code. e.g. date for code A should look like this and same for the others.

code     amount       date
-----------------------------
 A        1500     2013-02-03
 A        1800     2013-03-05
 A        1300     2013-03-05
 A        1300     2013-03-05

I know there are other similar posts for this question, but none of them give me the result above. I guess because selecting last value for each specific code is a bit tricky.

4
  • 1
    what is the version of your sql server Commented Oct 4, 2016 at 4:13
  • Something like UPDATE T SET [date] = U.[date] FROM myTable T CROSS APPLY (SELECT MAX([date]) FROM myTable WHERE code = T.code) U([date]) WHERE T.[date] IS NULL? Commented Oct 4, 2016 at 4:26
  • Do you want to UPDATE NULL values in the original table, or write a SELECT query that returns the result set without NULLs? Commented Oct 4, 2016 at 4:29
  • @TheGameiswar it is SQL Server 2014 Commented Oct 4, 2016 at 5:08

1 Answer 1

2

How about?

UPDATE mytable
SET date = date2
FROM mytable o
  CROSS APPLY
    (SELECT MAX(date) date2 FROM mytable i WHERE i.id=o.id group by id) ii
where o.date is null
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.