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

How can I subtract from a running total subquery in my query?

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

除了之前的付款金额,我已经创建了我需要的所有内容。我一直 运行ning 进入子查询错误

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 是我 运行 进入子查询错误的地方,因为我使用 <

感谢任何帮助。

您在子查询中出现错误的原因是因为它在投影中,因此它必须 return 一个单一的值。您的子查询将 return 多个值。它还将 return 所有先前的交易,除了 trantype 和 tran_dt 之外没有任何限制,这可能不是您真正想要的。

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

您可以通过多种不同的方式解决这个问题...

常见 Table 表达式 (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