表1:
Temp ResID Code Date
11 1 SPR
12 1 SPG 2009-10-05
13 1 SPR
14 1 SPG 2011-10-08
表2:
TempID Res ID InDate Out Date
21 1. 2009-10-05 2010-11-15
22 1. 2011-10-08 2011-11-09
表3 :(期望结果)
ResID Code Date
1 SPR 2010-11-15
1 SPG 2009-10-05
1 SPR 2011-11-09
1 SPG 2011-10-08
我有两张桌子。
我需要为代码为SPR的每一行的每个ID更新表1 Date列。表1日期列中的SPG值等于同一驻留的
的InDate列值请咨询查询。如何通过连接两个表(表1和表2以获取表3
)的查询来实现此目的答案 0 :(得分:1)
从选择语句编辑到更新
我认为这对你有用。请参阅SqlFiddle
Update
Table1
set
Table1.[Date] = Table2.OutDate
from
Table1
inner join
(
select
Temp,
ResID,
Code,
Date,
row_number() over(partition by ResID order by Temp) as RowId
from
Table1
where
Code = 'SPR'
) as SPR on Table1.Temp = SPR.Temp
inner join
(
select
ResID,
Code,
Date,
row_number() over(partition by ResID order by Temp) as RowId
from
Table1
where
Code = 'SPG'
) as SPG on SPG.RowId = SPR.RowId and SPG.ResID = SPR.ResID
inner join
Table2 on Table2.InDate = SPG.Date and Table2.ResID = SPG.ResID
答案 1 :(得分:1)
您可以删除所有SPR
行,然后生成它们:
delete Table1
where code = 'SPR';
insert Table1
(ResID, Code, [Date])
select t1.ResID
, 'SPR'
, OutDate
from Table1 t1
join Table2 t2
on t1.ResID = t2.ResID
and t1.[Date] = t2.InDate
where t1.Code = 'SPG';
答案 2 :(得分:0)
如果table2具有每个表的值,那么你可以使用table2,有点奇怪但你可以随时加入主表以获得适当的结果,如果你想
select Convert(varchar, indate, 102) as date, 'SPG' as code, resid from table2
union all
select convert(varchar, outdate, 102) as date, 'SPR' as code, resid from table2