从另一个表的值更新表的特定字段

时间:2016-09-11 17:19:17

标签: sql sql-server sql-server-2008 sql-server-2012

我有两张桌子:第一张桌子是: - Table 1

从这张表中我想 SUM 只有第3周的信息,即 pointsRewarded 小时字段到下表 TotalPoints TotalHours 字段。

我已经创建了表格。我只想更新下表。

enter image description here

请帮我查询一下,或者就如何解决这个问题给我一些建议。

非常感谢。

4 个答案:

答案 0 :(得分:0)

INSERT INTO [dbo].[Table2] (
    [EmployeeID]
    ,[Employee Name]
    ,[TotalPoints]
    ,[TotalHours]
    )
SELECT  
    [EmployeeID]
    ,[Employee Name]
    ,SUM(pointRewarded) as [TotalPoints]
    ,SUM([Hours]) as [TotalHours]
FROM [dbo].[Table1]
WHERE WeekNumber='week3'
GROUP BY   
    [EmployeeID]
    ,[Employee Name]

GO

答案 1 :(得分:0)

我猜第一个表已经存在,你想要添加第3周的值:

update t2
    set pointsrewarded = t1.pointsrewarded + t2.pointsrewarded,
        hours = t1.hours + t2.hours
    from t2 join
         (select t1.employeeid, sum(pointsrewarded) as pointsrewarded
                 sum(hours) as hours, 
          from t1
          where t1.weeknumber = 'week3'
          group by t1.employeeid
         ) t1
         on t2.employeeid = t1.employeeid;

答案 2 :(得分:0)

在这种情况下,您可以使用cte

;WITH cte_1
         as (SELECT employeeid
                   ,SUM(pointsrewarded) as Week3TotalPoints
                   ,SUM([hours]) as Week3TotalHours
              FROM YourSourceTable  
              WHERE WeekNumber = 'week3'
              GROUP BY employeeid)
        UPDATE d
        SET d.TotalPoints=d.TotalPoints+c.Week3TotalPoints,
            d.TotalHours=d.TotalHours+c.Week3TotalHours
        FROM cte_1 c
         JOIN YourDestinationTable d on c.employeeid=d.employeeid

答案 3 :(得分:0)

试试这个

UPDATE table2 
SET    totalpoints = totalpoints+(SELECT Sum(E.pointrewarded) 
                      FROM   table1 E 
                      WHERE  E.weeknumber = 'week3' 
                             AND E.employeeid = employeeid), 
       totalhours = totalhours+(SELECT Sum(E.hours) 
                     FROM   table1 E 
                     WHERE  E.weeknumber = 'week3' 
                            AND E.employeeid = employeeid)