我有两个表,我想将当前行从该表更新到主表,我是一个DBA,所以对我来说,我最终会写一个大循环,所以想着是否有人可以帮助我。所以基本上我想从表1中更新表2的值(latestTimestamp和count),表2中的catch应该从表1的最新计数中增加,如果表2计数为48且表1的最新计数为1则应该添加1到48,表2中的值应为49,表1中包含最新时间戳。我希望我有意义。
以下是数据
表1(表名)
Column > DBName Proc Name CTimeStmp Count LatestTimeStmp Calls
Data >
DB_US, upGetSelfServiceHelp, 2011-02-10 11:37:22.490, 48, 2013-06-17 07:21:41.480, 0
DB_US, upGetSelfServiceHelp, 2011-02-10 11:37:22.490, 1, 2013-06-17 14:18:33.997, 0
表2(表名)
Column > DBName Proc Name CTimeStmp Count LatestTimeStmp Calls
Data >
DB_US upGetSelfServiceHelp 2011-02-10 11:37:22.490 48 2013-06-17 07:21:41.480 0
答案 0 :(得分:2)
这能满足您的需求吗?
update [Table 2] set
[LatestTimeStmp] = (select max([LatestTimeStmp]) from [Table 1] t1 where t1.DBName = t2.DBName and t1.ProcName = t2.ProcName),
[Count] = (select sum([Count]) from [Table 1] t1 where t1.DBName = t2.DBName and t1.ProcName = t2.ProcName)
from
[Table 2] t2
或者如果子查询的重复你错了,这也是一样的:
update [Table 2] set
LatestTimeStmp = t1.LatestTimeStmp,
[Count] = t1.Count
from
[Table 2] t2
join (
select
DBName,
ProcName,
max(LatestTimeStmp) LatestTimeStmp,
sum(Count) [Count]
from
[Table 1]
group by
DBName,
ProcName
) t1 on t1.DBName = t2.DBName and t1.ProcName = t2.ProcName