0

我有两个表,我想将该表中的当前行更新到主表,我是一名 DBA,所以对我来说,我最终会编写一个大循环,所以我想是否有人可以帮助我。所以基本上我想从 (latestTimestamp and count) 的表 1 值更新表 2,并且捕获的是表 2 计数应该从表 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
4

1 回答 1

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
于 2013-06-17T20:19:38.573 回答