SQL查询-数据与日期条件比较,是否存在,值变化情况

SQL query -data compare with date criteria , exist , value change condition

create table #temp (
user_id [int]  NOT NULL,
date [Date] NOT NULL,
typeid [int] NOT NULL,
fieldid [int] NOT NULL,
valueid [int]  NOT NULL
);

create table #temp1 (
user_id [int]  NOT NULL,
date [Datetime] NOT NULL,
typeid [int] NOT NULL,
fieldid [int] NOT NULL,
valueid [int]  NOT NULL
);

insert into #temp values (1,'2020-01-25',9876,12, 1);
insert into #temp values (1,'2020-01-25',9876,13, 1);


insert into #temp1 values (1,'2020-05-20',9876,12, 1); -- same row as compared with excluding date condition so ignore this
insert into #temp1 values (1,'2020-05-20',9876,14, 1);



output can be #temp or in different table 

user_id date     typeid     fieldid valueid
1   2020-01-25    9876         12   1
1   2020-01-25    9876         13   1
1   2020-05-20    9876         14   1   -- new row and the value is 1
1   2020-05-20    9876         13   0   -- fieldid 13 value is 1 and not in #temp1 so added here with value 0



MERGE
    #temp AS t
USING
(
    SELECT * from #temp1  AS st
) AS s
ON
    t.[user_id] = s.[user_id]
    AND
        t.[typeid] = s.[typeid]
    AND 
        s.fieldid = t.fieldid
    AND 
       s.valueid = t.valueid

WHEN MATCHED  THEN
    DELETE

WHEN NOT MATCHED BY SOURCE  AND t.[valueid] = 1 THEN
UPDATE SET
        [user_id] = t.[user_id],
        [date] = t.[date],  -- here i want to set the date of the source table of other fields
        [typeid] = t.[typeid],
        [fieldid] = t.[fieldid],
        [valueid] = 0

WHEN NOT MATCHED BY TARGET THEN
INSERT([user_id], [date], [typeid], [fieldid], [valueid])
    VALUES(s.[user_id], s.[date], s.[typeid], s.[fieldid], [valueid]);

无法将其他字段的源日期设置为 WHEN NOT MATCHED BY SOURCE 中的查询。有没有什么办法或任何其他方法来获得想要的输出?

为了完成这项工作,我为给定用户更新了#temp1 中的日期。

请告诉我是否有任何其他方法可以获得所需的输出。

p.s。编辑了这个问题以使其简单明了

我认为 merge 不可能做到这一点。您可以尝试以下方法:

insert into #temp
select * from #temp1 s
where not exists (select * from #temp t where t.[user_id] = s.[user_id] AND t.[typeid] = s.[typeid] AND s.fieldid = t.fieldid AND s.valueid = t.valueid)
union
select distinct s.user_id, '2099-12-31', s.typeid, s.fieldid, 0 from #temp s
left join #temp1 t on t.[user_id] = s.[user_id] AND t.[typeid] = s.[typeid] AND s.fieldid = t.fieldid AND s.valueid = t.valueid
where t.user_id is null

update t
set [date] = t1.[date]
from #temp t
join (select top 1 * from #temp1) t1 on t1.user_id = t.user_id
where t.[date] = '2099-12-31'

select * from #temp

请查找数据库<>fiddle here.