How to update column values ββin one query if the value is null and then update with a previous nonzero value
I have a table Salesorder
and the structure of the table is like this.
Create table Salesorder(SOID int identity, quantity numeric(18,2))
The values ββin the table are shown below.
insert into Salesorder values(100)
insert into Salesorder values(Null)
insert into Salesorder values(200)
insert into Salesorder values(300)
insert into Salesorder values(Null)
insert into Salesorder values(Null)
insert into Salesorder values(500)
insert into Salesorder values(Null)
So, I want to update this table in such a way that when I execute the select query, I have to find the result below.
Expected Result:
100 100 200 300 300 300 500 500
This means that all zero values ββmust be updated with the previous non-zero values.
source to share
This request will be UPDATE
as expected
UPDATE Salesorder1 SET Salesorder1.quantity =
CASE WHEN Salesorder1.quantity IS NULL
THEN (
SELECT TOP 1 SalesOrder2.quantity
FROM Salesorder AS SalesOrder2
WHERE
SalesOrder2.quantity IS NOT NULL AND
SalesOrder2.SOID < SalesOrder1.SOID
ORDER BY SalesOrder2.SOID DESC
)
END
FROM Salesorder AS SalesOrder1
WHERE SalesOrder1.quantity IS NULL
Operator CASE
SalesOrder2.quantity IS NOT NULL
AND SalesOrder2.SOID < SalesOrder1.SOID
ORDER BY SalesOrder2.SOID DESC
replaces the values NULL
with the previous value, and the clause WHERE
gives the value NOT NULL
in descending order.
source to share