如何根据字段的总和更新记录,然后使用总和在sql中计算新值
以下是我试图通过迭代记录来完成的操作。
如果可能的话,我希望有一个更优雅的解决方案,因为我确信这不是在 sql 中执行此操作的最佳方法。
set @counter = 1
declare @totalhrs dec(9,3), @lastemp char(7), @othrs dec(9,3)
while @counter <= @maxrecs
begin
if exists(select emp_num from #tt_trans where id = @counter)
begin
set @nhrs = 0
set @othrs = 0
select @empnum = emp_num, @nhrs = n_hrs, @othrs = ot_hrs
from #tt_trans
where id = @counter
if @empnum = @lastemp
begin
set @totalhrs = @totalhrs + @nhrs
if @totalhrs > 40
begin
set @othrs = @othrs + @totalhrs - 40
set @nhrs = @nhrs - (@totalhrs - 40)
set @totalhrs = 40
end
end
else
begin
set @totalhrs = @nhrs
set @lastemp = @empnum
end
update #tt_trans
set n_hrs = @nhrs,
ot_hrs = @othrs
where id = @counter and can_have_ot = 1
end
set @counter = @counter + 1
end
谢谢
Below is what I'm trying to do with by iterating through the records.
I would like to have a more elegant solution if possible since I'm sure this is not the best way to do it in sql.
set @counter = 1
declare @totalhrs dec(9,3), @lastemp char(7), @othrs dec(9,3)
while @counter <= @maxrecs
begin
if exists(select emp_num from #tt_trans where id = @counter)
begin
set @nhrs = 0
set @othrs = 0
select @empnum = emp_num, @nhrs = n_hrs, @othrs = ot_hrs
from #tt_trans
where id = @counter
if @empnum = @lastemp
begin
set @totalhrs = @totalhrs + @nhrs
if @totalhrs > 40
begin
set @othrs = @othrs + @totalhrs - 40
set @nhrs = @nhrs - (@totalhrs - 40)
set @totalhrs = 40
end
end
else
begin
set @totalhrs = @nhrs
set @lastemp = @empnum
end
update #tt_trans
set n_hrs = @nhrs,
ot_hrs = @othrs
where id = @counter and can_have_ot = 1
end
set @counter = @counter + 1
end
Thx
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这很接近您想要的,但是一旦您回答了我关于您真正想要实现的目标的评论,就需要进行一些调整。
This is close to what you want, but will need to be tuned a bit once you answer my comment about what you are really trying to achieve.
看起来您正在迭代,因为您必须跨多个记录跟踪给定员工的总工时。您可以改为使用内部选择来汇总每个员工的小时数,并将该选择加入到 #tt_trans 表中。从该连接写入更新,并将逻辑放入更新列的 CASE 语句中。
It looks like you are iterating because you have to keep track of the total hours for a given employee across multiple records. You can instead use an interior select to sum the hours for each employee, and join that select to your #tt_trans table. Write your update from that join, and put your logic in CASE statements for the updating columns.
基本上我修改了该期间最后一个日期的时间并进行了相应调整。感谢两位的回复。这两个回复都让我想到了我的。
Basically I took the modified the hours of the last date in the period and adjusted accoringly. Thanks to the both of you who responded. Both replies led me to mine.