SQL-SERVER:外部Select的每一行的子查询

时间:2018-06-04 13:49:40

标签: sql sql-server stored-procedures

我正在创建一个存储过程,其中我希望为外部select的每一行执行子查询。

每个帐户都有一些存储在同一列中的付款和收据。 对于每个帐户,我想生成此列的总和 子查询创建两列 PAYMENTS_SUM RECEIPTS_SUM 。问题是,即使生成摘要,它们也只执行一次。经过一些搜索,我发现这是预期的行为。

但我如何为每个 ACC.ACCOUNTID

生成这些总和
BEGIN
SET NOCOUNT ON


SELECT  DiSTINCT

ACC.ACCOUNT,
BM.CCY,
ACC.SEG,     

(SELECT SUM(BM.ADJUSTMENT) AS PAYMENTS_SUM FROM [dbo].[Accounts] ACC   
 LEFT join [dbo].[BalanceMovements] BM ON BM.ACCOUNTID = ACC.ACCOUNTID collate database_default  
 WHERE 
 ACC.Account = ACC.ACCOUNT And
 Month(BM.COB) = MONTH(GETDATE()) 
 AND 
 YEAR(BM.COB) = YEAR(GETDATE())
 AND
 BM.ADJUSTMENT > 0
 )
 AS PAYMENTS_SUM,

(SELECT SUM(BM.ADJUSTMENT) AS PAYMENTS_SUM FROM [dbo].[Accounts] ACC  
 LEFT join [dbo].[BalanceMovements] BM ON BM.ACCOUNTID = ACC.ACCOUNTID collate database_default   
 WHERE 
 ACC.Account = ACC.ACCOUNT AND
 Month(BM.COB) = MONTH(GETDATE()) 
 AND 
 YEAR(BM.COB) = YEAR(GETDATE())
 AND
 BM.ADJUSTMENT < 0
 )
 AS RECEIPTS_SUM,

ACC.SystemAccount,
ACC.ENTITY,
ACC.BusinessGroup
FROM [dbo].[Accounts] ACC  
LEFT join [dbo].[BalanceMovements] BM ON BM.ACCOUNTID = ACC.ACCOUNTID collate database_default  
WHERE     
Month(BM.COB) = MONTH(GETDATE()) 
AND 
YEAR(BM.COB) = YEAR(GETDATE()) 

END

enter image description here

正如您所看到的,每个帐户的结果都具有相同的值。

1 个答案:

答案 0 :(得分:2)

这个答案是一个推测,但希望能够更接近你想要的。这个想法是你只想根据不同的条件有条件地汇总调整金额。其他非聚合列几乎可以用于骑行,因此我们可以将它们添加到GROUP BY子句中。

SELECT
    ACC.ACCOUNT,
    BM.CCY,
    ACC.SEG,
    ACC.SystemAccount,
    ACC.ENTITY,
    ACC.BusinessGroup,
    SUM(CASE WHEN BM.ADJUSTMENT > 0 THEN BM.ADJUSTMENT ELSE 0 END) AS PAYMENTS_SUM,
    SUM(CASE WHEN BM.ADJUSTMENT <= 0 THEN BM.ADJUSTMENT ELSE 0 END) AS RECEIPTS_SUM
FROM [dbo].[Accounts] ACC   
LEFT join [dbo].[BalanceMovements] BM
    ON BM.ACCOUNTID = ACC.ACCOUNTID collate database_default
WHERE
    MONTH(BM.COB) = MONTH(GETDATE()) AND YEAR(BM.COB) = YEAR(GETDATE())
GROUP BY
    ACC.ACCOUNT,
    BM.CCY,
    ACC.SEG,
    ACC.SystemAccount,
    ACC.ENTITY,
    ACC.BusinessGroup;