SQL Mathematical Operation使用两个表并更新新值

时间:2016-01-28 16:24:43

标签: sql sql-server

我有两张桌子

Table 01
========
**ApprovedLeave**
UserName varchar
DateFrom varchar
DateTo varchar
NumofWorkingDays int
LeaveType varchar
Dept varchar
LStatus1 int 
LStatus2 int

Table02
=======
**LeaveEntitlement**
UserName varchar
TotalLeaveRemaining int

我需要获取NumofWorkingDays int值并从表02中的TotalLeaveRemaining值中减去它并将其保存在同一位置。请帮忙。到目前为止这是我的代码。

select (A.TotalLeaveRemaining-B.NumofWorkingDays)
from LeaveEntitlement as A join 
     ApprovedLeave as B
     on A.UserName= B.UserName

1 个答案:

答案 0 :(得分:0)

加入只是一个开始。您还需要为每个用户聚合,然后执行算术:

select A.UserName, (A.TotalLeaveRemaining - SUM(B.NumofWorkingDays))
from LeaveEntitlement as A join 
     ApprovedLeave as B
     on A.UserName = B.UserName
group by A.UserName, A.TotalLeaveRemaining;

在SQL Server中,您将使用类似的查询进行更新:

update le
    set TotalLeaveRemaining = al.sum_NumofWorkingDays
    from LeaveEntitlement le join
         (select UserName, sum(NumofWorkingDays) as sum_NumofWorkingDays
          from ApprovedLeave
          group by UserName
         ) al
         on le.UserName = al.UserName;