SQL 将多个 select 语句组合成一个查询

标签 sql sql-server sql-server-2008

我有以下查询,它获取未清发票总额并删除总付款和贷方票据以获得未清余额。

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/

相关文章:

sql服务器: Get OHLC in one query with n recodrs

c++ - 修改sys.database_mirroring中的mirroring_partner_instance名称

c# - SQL Server : cannot connect from local website (SQL Network Interfaces, 错误:26 - 定位指定的服务器/实例时出错)

sql - 如何在 T-SQL 中删除空格前的某些字符?

android - Android 上使用带空格参数的 SQLite 查询

sql - 选择使用联合查询

mysql - 数据库性能调整有哪些资源?

sql - SQL Server查询性能-消除了对哈希匹配(内部联接)的需求

sql - 如何对表施加约束以确保表子集中只有一个 bool 列为真?

mysql - 第 1 列 "commrate"的值超出范围