表A,表B。
TableA具有以下记录。
id Name Address phone RecordType ProcessStatus 1 ABC HYD 123 INSERT 4 2 PQR IND 111 INSERT 4 1 ABC NULL 6780 UPDATE 3
我只想选择RECORD_TYPE ='UPDATE'类型。如果RecordType = UPDATE的任何值具有NULL值,则应将其与INSERT TYPE记录进行比较,并携带该值而不是填充NULL。我必须以应反映如下的方式填充表B。
id Name Address phone RecordType ProcessStatus 1 ABC HYD 6780 UPDATE 3
以下是我尝试过的内容。
SELECT COALESCE(A.ID,B.ID),
COALESCE(A.ADDRESS,B.ADDRESS),
COALESCE(A.PHONE,B.PHONE),
COALESCE(A.RECORD_TYPE,B.RECORD_TYPE),
COALESCE(A.STATUS,B.STATUS)
FROM #TEMP A INNER JOIN #TEMP B
ON A.ID=B.ID
WHERE A.RECORD_TYPE='UPDATE'
下面是我得到的。
ID ADDRESS PHONE RECORD_TYPE STATUS 1 ABC 123 UPDATE 3 1 ABC NULL UPDATE 3
答案 0 :(得分:1)
这可能会给您您所需要的
insert into tableC(id, name, address, phone, recordType, processstatus)
SELECT * FROM (
select i.id, CASE WHEN u.name IS NULL THEN i.name ELSE u.name END name
,CASE WHEN u.address IS NULL THEN i.address ELSE u.address END address
,CASE WHEN u.phone IS NULL THEN i.phone ELSE u.phone END phone
,CASE WHEN u.recordType IS NULL THEN i.recordType ELSE u.recordType END recordType
,CASE WHEN u.processstatus IS NULL THEN i.processstatus ELSE u.processstatus END processstatus
from tableA i
left join tablea u on u.id = i.id and u.RecordType = 'UPDATE'
where i.RecordType = 'INSERT'
union
SELECT u.id,u.name,u.address,u.phone,u.RecordType, u.ProcessStatus
FROM tableA u
WHERE NOt EXISTS(SELECT * FROM tableA i where i.id=u.id and i.RecordType = 'INSERT')) f
WHERE f.recordType = 'UPDATE'
order by f.id