I am using SQL Server v18.
I need to update a temp table and replace the values in Column_B that are equal to zero with the non-zero values, based on Column_A.
This is how the initial table looks like:
| Column_A | Column_B |
| ------------ | ------------ |
| ABC | 0 |
| ABC | 123 |
| ABC | 0 |
| DEF | 456 |
| DEF | 0 |
| DEF | 0 |
| GHI | 123 |
| GHI | 0 |
This is what I am expecting the final table to look like:
Column_A | Column_B |
---|---|
ABC | 123 |
ABC | 123 |
ABC | 123 |
DEF | 456 |
DEF | 456 |
DEF | 456 |
GHI | 123 |
GHI | 123 |
Here is the code that I have tried so far.
UPDATE #temp_table
SET Column_B = CASE
WHEN EXISTS (SELECT *
FROM #temp_table AS t1
WHERE Column_B <> 0
AND Column_A = t1.Column_A)
THEN Column_B
ELSE 0
END
WHERE Column_B = 0;
This is the message from the above code:
5 rows affected
However, when I validate the results, the table remains unchanged. The non-zero values have not been replaced.
I will appreciate any help. Thanks.
2条答案
按热度按时间f87krz0w1#
This answer follows the requirement you described in comments:
I will have to select the correct value, which would be the first record written, based on a DateTime column
I think you will do better to edit your question and adjust the sample data rather than writing this as a comment that people might not read.
Anyway, this query using
FIRST_VALUE
will fetch the first of Column B for each value in Column A which is notNULL
and not0
:The
ORDER BY yourdate
clause covers your requirement to take "the first record written" because this is the row having the earliest date. Above query can be used in the update command:The
WHERE
clause in the update command makes sure to update those rows only whereColumn B
is0
.See this sample fiddle .
It shows the result for some data similar to yours, but extended by some other rows. Thus, it points out how this idea works.
kokeuurv2#
Please try this query with correlated UPDATE (update...join)