帮助简单的SQL查询

时间:2011-01-20 21:39:36

标签: sql sql-server

我有一个相当大的SPROC我正在努力。好吧,就我而言很大,因为我在很长一段时间内都没有写过SQL。无论如何,我想让这个Update语句工作:

update @salesCommission
set LineAmountWithCashDiscount = (LineAmount - ((LineAmount/ (
   select SUM(LineAmount)
   FROM  @salesCommission
   WHERE InvoiceNumber='00072766')) * CashDiscountAmount))

我的问题是我需要替换:

WHERE InvoiceNumber ='00072766'

子句使发票号码不是硬编码的。相反,它应该只是正在更新的当前行的发票号。

有人能告诉我如何重新编写此更新查询,以便为正在更新的当前行选择LineAmount的总和吗?

2 个答案:

答案 0 :(得分:3)

update S
SET LineAmountWithCashDiscount = S.LineAmount - (S.LineAmount / I.Total) * CashDiscountAmount
FROM @salesCommission S
inner join
(
select InvoiceNumber,
    CASE WHEN SUM(LineAmount) = 0 THEN 1 ELSE SUM(LineAmount) END as Total 
from @salesCommission
group by InvoiceNumber
) I on I.InvoiceNumber = S.InvoiceNumber

编辑:当0到达时,将“总数”变为1的情况#Div / 0错误

答案 1 :(得分:0)

如果你在一个被触发器调用的存储过程中这样做...

update @salesCommission 
set LineAmountWithCashDiscount = 
(LineAmount - ((LineAmount/ (select SUM(LineAmount) 
FROM  @salesCommission WHERE InvoiceNumber=(Select InvoiceNumber from Inserted)
)) * CashDiscountAmount))