简体   繁体   中英

SQL assign value for join purpose to null field without update

With this sample data...

c1  c2  c3
10  a   10a
11  a   **NULL**
12  a   **NULL**
13  b   13b
13  b   **NULL**
etc..

I want to assign c3 value to rows where it is NULL and c2 value is the same, but do not wish to actually update that value in table, only use it to join to another table while select runs.

I am able to do it using inner select and join, but I want to save as much processing power as possible because amount of data is huge and thought that some use of ISNULL or COALESCE should be able to do it, but I don't have enough experience to figure it on my own yet, or even say if it is possible. What do you think?

 select
    a.c1,
    a.c2,
    coalesce( a.c3, b.c3) as c3
   from table1 a
      left join table1 b
       on a.c2 = b.c2
             an  a.c3 is null
             and b.c3 is not null

this will work with the data that you have however if there is more than one row that is not null for c3 for a given c2 it will cause problems

If your DB supports max() over you can also do this

SELECT c1,
       c2,
       coalesce(c3, MAX(C3) over (partition by c2)) c3
from table1

demo

A sample pseudo code which i often use in my Query.

DECLARE @USER_ID AS VARCHAR(256)
SELECT @USER_ID = 'abc'


select *
from CC
INNER JOIN adm_co_users CR_US WITH(NOLOCK) ON ISNULL(CR_US.original_userID,'') =
        (CASE ISNULL(CC.Createdby,'')   WHEN '' THEN @USER_ID
        ELSE CC.Createdby END ) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM