我有一个表,我想使用Visual Basic 6平台的单个SQL语句来选择和减去基于where子句的summed列。以下是说明 这是一个样本表,可以更好地解释:
ID Deposit Withdrawal Date ACC01 1000 0 10/10/2012 ACC01 2000 0 1/1/2013 ACC02 3000 0 10/10/2012 ACC02 4000 0 1/1/2013 ACC01 0 1000 12/12/2012 ACC02 0 3000 12/12/2012
我希望将日期小于2013年1月1日的存款列中的值汇总为DepositBefore
还将提取列中的值汇总为日期小于2013年1月1日的WithDrawalBefore
然后从WithdrawalBefore
(即DepositBefore
)
BalanceBefore = DepositBefore - WithrawalBefore
同样,将日期> = 2013年1月1日的存款列中的总和作为DepositAfter
另请将Withdrawal
列中的值与WithdrawalAfter
的日期> = 1/1/2013相加
这样(BalanceAfter = DepositAfter - WithdrawalAfter
)
最后计算BalanceForInterest = BalanceBefore + BalanceAfter
。如果单个查询可以解决此问题,请更喜欢
以下是我尝试但未成功的代码。
With rsSaving
.Open "SELECT SUM(SUM(Deposit)-SUM(Withdrawal)) AS BalanceBefore FROM tblSaving WHERE ID = 'ACC01' AND Date < #1/1/2013# GROUP BY ID, (SELECT SUM(SUM(Deposit)-SUM(Withdrawal)) AS BalanceAfter FROM tblSaving WHERE ID='ACC01' AND Date >= #1/1/2013# GROUP BY ID)",conDB, adOpenDynamic, adLockOptimistic
.close
End With
set rsSaving = Nothing
rsSaving是一个ADO对象,而conDB是我的连接。感谢
答案 0 :(得分:0)
这是SQL查询。您可能必须更改数据库的语法(SQL,Access等)。您不需要GroupBy
因为您获得了单个值。给定您的示例数据,此查询返回2000。
SELECT
(SELECT SUM(Deposit-Withdrawal) AS Total FROM tblSaving WHERE ID = 'ACC01' AND Date < '1-1-2013')
+ (SELECT SUM(Deposit-Withdrawal) AS Total FROM tblSaving WHERE ID = 'ACC01' AND Date >= '1-1-2013')
AS BalanaceAfter
答案 1 :(得分:0)
你可以像
一样写declare @BalanceBefore int
set @BalanceBefore = (select sum(deposit ) from table where date < 1/1/2013)
declare @WithdrawalAfter int
set @WithdrawalAfter = (select sum(WithdrawalAfter ) from table where date > 1/1/2013)
declare @res int
set @res = @BalanceBefore - @WithdrawalAfter
print @res
尝试这样的事情。还要检查日期比较