如何从查询中正在运行的总计子查询中减去?

时间:2018-12-27 20:29:28

标签: sql-server-2008 sum case invoice running-total

我正在尝试创建一个案例,如果有以前的付款,我可以从选定的金额日期范围中扣除。

除了以前的付款金额,我已经创建了所有需要的东西。我一直遇到子查询错误

SELECT 
   acctnmbr
  ,amount*commission/100
  ,(select amount*commission/100 from transactions where trantype=0001 and tran_dt < @startdate) as Previous_Payments
FROM transactions
  where trantype=0001 and tran_dt between @startdate and @enddate

Previous_Payments是我因为使用​​<< / p>而遇到子查询错误的地方

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

之所以会在子查询中出现错误,是因为它在投影中,因此它必须返回单个值。您的子查询将返回多个值。除了trantype和tran_dt(可能不是您真正想要的)以外,它还将返回所有先前的交易,没有任何约束。

我还假设您想要所有内容的总和,因为根据您提供的简短描述,这似乎很有意义。但是,如果您按照Gordon Linoff的建议提供一些其他信息,我将很乐意更新我的答案。

您可以用多种不同的方式来攻击它...

公用表表达式(CTE):

WITH PriorPayments AS
SELECT acctnmbr, amount*commission/100 as payment from transactions where trantype=0001 and tran_dt < @startdate

SELECT trx.acctnmbr, 
       sum(trx.amount*trx.commission/100) as total_payment, 
       sum(ISNULL(pp.payment,0)) as prior_payment 
FROM transactions trx 
LEFT JOIN PriorPayments pp ON trx.acctnmbr=pp.acctnmbr
WHERE trx.trantype=0001 
AND trx.tran_dt BETWEEN @startdate and @enddate
GROUP BY trx.acctnmbr

子查询:

SELECT trx.acctnmbr, 
       sum(trx.amount*trx.commission/100) as total_payment, 
       sum(ISNULL(pp.payment,0)) as prior_payment 
FROM transactions trx 
LEFT JOIN (
    SELECT acctnmbr, amount*commission/100 as payment from transactions where trantype=0001 and tran_dt < @startdate
) AS pp ON trx.acctnmbr=pp.acctnmbr
WHERE trx.trantype=0001 
AND trx.tran_dt BETWEEN @startdate and @enddate
GROUP BY trx.acctnmbr