我有以下查询,它获取未清发票总额并删除总付款和贷方票据以获得未清余额。
declare @tInv decimal(19, 2)
declare @tCrn decimal(19, 2)
declare @tPay decimal(19, 2)
set @tInv =
(
SELECT SUM(ST_Unallocated) from Transactions where ST_COPYCUST = 'LOEH001' and ST_TRANTYPE = 'INV'
)
set @tCrn =
(
SELECT SUM(ST_Unallocated) from Transactions where ST_COPYCUST = 'LOEH001' and ST_TRANTYPE = 'CRN'
)
set @tPay =
(
SELECT SUM(ST_Unallocated) from Transactions where ST_COPYCUST = 'LOEH001' and ST_TRANTYPE = 'PAY'
)
declare @currBal decimal(19, 2)
set @currBal =
(
SELECT @tInv - @tPay - @tCrn
)
select @currBal
我想将上面的查询与下面的查询结合起来,以显示每个客户的未清余额总额 -
select
c.AccountNumber,
c.CustomerID,
c.FullName,
ct.Description as 'CustomerTypeDesc',
c.TelNumber,
c.EmailAddress
from Customers c
inner join CustomerTypes ct on c.CustomerType = ct.TypeID
left join Transactions t on c.AccountNumber = ST_COPYCUST
where c.StatusID = 0 or c.StatusID = 1
有什么想法可以做到这一点吗?
谢谢
最佳答案
尝试以下查询。我做了一些假设,并从您的主查询中删除了 Transactions
表上的联接,因为我认为这超出了要求。使用这些内联查询的优点在于,如果需要,您可以返回多个客户(通过删除 c.AccountNumber 上的过滤器):
SELECT
c.AccountNumber
, c.CustomerID
, c.FullName
, ct.Description as 'CustomerTypeDesc'
, c.TelNumber
, c.EmailAddress
, (SELECT SUM(ST_Unallocated) from Transactions where ST_COPYCUST = c.AccountNumber and ST_TRANTYPE = 'INV') -
(SELECT SUM(ST_Unallocated) from Transactions where ST_COPYCUST = c.AccountNumber and ST_TRANTYPE = 'CRN') -
(SELECT SUM(ST_Unallocated) from Transactions where ST_COPYCUST = c.AccountNumber and ST_TRANTYPE = 'PAY') AS BalanceToPay
FROM Customers c
INNER JOIN CustomerTypes ct on c.CustomerType = ct.TypeID
WHERE c.StatusID IN (0,1) AND c.AccountNumber = ST_COPYCUST
关于SQL 将多个 select 语句组合成一个查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22402374/