使用多个表循环遍历数据库(并返回 SUM)

Looping through a database using multiple tables (and returning a SUM)

我目前有一个数据库,其中包含公寓所有者在一组公寓中进行的 table 笔交易

当我运行这个查询时:

SELECT Account, Sum([Debit]) - SUM([Credit]) as Balance
  FROM [Boschendal Manor BC].[dbo].[PostGL] as PostGl 
  Inner JOIN [Boschendal Manor BC].[dbo].[Client] as Client on Client.DCLink = DrCrAccount
  where DrCrAccount = '2' and AccountLink <> '104' and TxDate < '2021/11/30' Group By Account

它显示单元 1 的 11 月 30 日之前的帐号和余额 - 如果我将 DrCrAccount 增加到 3,它会显示相同的单元 2 ...等等

所以我需要循环遍历数据库中的客户数量并获取每个帐号和余额。

我想出了如何获取客户数量,像这样:

select COUNT(*) from [Boschendal Manor BC].[dbo].[Client] where DCBalance is not NULL

这个return秒130

有谁知道我如何循环 PostGL table 只要客户 table 是 ,然后 return 日期是借方和贷方的总和2021/11/30 之前?

DrCrAccount 添加到 group by 并删除过滤器将为您提供所有客户数据。像这样:

SELECT   DrCrAccount , Account, Sum([ Debit ]) - SUM([ Credit ]) as Balance
  FROM [ Boschendal Manor BC ] . [ dbo ] . [ PostGL ] as PostGl
 Inner JOIN [ Boschendal Manor BC ] . [ dbo ] . [ Client ] as Client
    on Client.DCLink = DrCrAccount
 where  AccountLink <> '104'
   and TxDate < '2021/11/30'
 Group By Account , DrCrAccount 

编辑关于您对此答案的评论:您不能直接过滤像 balance 这样的别名。

一种解决方案是将其作为子查询,然后像这样过滤它:

Select * from 
(
SELECT   DrCrAccount , Account, Sum([ Debit ]) - SUM([ Credit ]) as Balance
  FROM [ Boschendal Manor BC ] . [ dbo ] . [ PostGL ] as PostGl
 Inner JOIN [ Boschendal Manor BC ] . [ dbo ] . [ Client ] as Client
    on Client.DCLink = DrCrAccount
 where  AccountLink <> '104'
   and TxDate < '2021/11/30'
 Group By Account , DrCrAccount
) tbl
where tbl.Balance > 200