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

时间:2014-03-14 10:26:55

标签: 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

我有什么想法可以做到这一点吗?

由于

2 个答案:

答案 0 :(得分:2)

尝试以下查询。我做了一些假设并从主查询中移除了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

答案 1 :(得分:0)

希望没有破坏它,应该比子查询更快:

SELECT
 c.AccountNumber
, c.CustomerID
, c.FullName
, ct.Description as 'CustomerTypeDesc'
, c.TelNumber
, c.EmailAddress
, SUM(CASE WHEN ST_TRANTYPE = 'INV' THEN t.ST_Unallocated ELSE 0 END) AS tInv
, SUM(CASE WHEN ST_TRANTYPE = 'CRN' THEN t.ST_Unallocated ELSE 0 END) AS tCRN
, SUM(CASE WHEN ST_TRANTYPE = 'PAY' THEN t.ST_Unallocated ELSE 0 END) AS tPAY
, SUM(CASE WHEN ST_TRANTYPE = 'INV' THEN t.ST_Unallocated ELSE 0 END) - 
    SUM(CASE WHEN ST_TRANTYPE = 'PAY' THEN t.ST_Unallocated ELSE 0 END) -
    SUM(CASE WHEN ST_TRANTYPE = 'CRN' THEN t.ST_Unallocated ELSE 0 END) as currBal
FROM Customers c
INNER JOIN CustomerTypes ct on c.CustomerType = ct.TypeID
LEFT JOIN Transactions t on c.AccountNumber = t.ST_COPYCUST
WHERE c.StatusID = 0 or c.StatusID = 1 AND  c.AccountNumber = ST_COPYCUST
GROUP BY  c.AccountNumber
, c.CustomerID
, c.FullName
, ct.Description
, c.TelNumber
, c.EmailAddress