累计总数基于两列

时间:2017-10-27 14:51:54

标签: sql sql-server sap

所以我希望在我的查询中添加一个额外的列,根据信用卡/借记卡列计算累积余额。

到目前为止,我的查询看起来像这样:

 SELECT T1.[RefDate], T1.[TransId], T1.[BaseRef], T1.[LineMemo], T3.[Dscription], T1.[Debit], T1.[Credit], T4.[AcctName]
    FROM OJDT T0
    right JOIN JDT1 T1 ON T0.TransId = T1.TransId
    left JOIN OPCH T2 ON T0.TransId = T2.TransId
    left JOIN PCH1 T3 ON T3.DocEntry = T2.DocEntry
    left JOIN OACT T4 ON T1.Account = T4.AcctCode
    WHERE T4.[AcctCode] = [%0] AND
    T1.[RefDate] BETWEEN [%1] AND [%2]

2 个答案:

答案 0 :(得分:1)

您可以使用窗口SUM

SELECT T1.[RefDate], T1.[TransId], T1.[BaseRef], T1.[LineMemo], T3.[Dscription], 
    T1.[Debit], T1.[Credit], T4.[AcctName],
    SUM(ISNULL(Debit,0)+ISNULL(Credit,0)) OVER(PARTITION BY ... ORDER BY refDate)
FROM OJDT T0
right JOIN JDT1 T1 ON T0.TransId = T1.TransId
left JOIN OPCH T2 ON T0.TransId = T2.TransId
left JOIN PCH1 T3 ON T3.DocEntry = T2.DocEntry
left JOIN OACT T4 ON T1.Account = T4.AcctCode
WHERE T4.[AcctCode] = [%0] AND
    T1.[RefDate] BETWEEN [%1] AND [%2];

如果Debit列包含正值,则需要在其前面添加-

答案 1 :(得分:1)

OVER周围的文档:https://msdn.microsoft.com/en-us/library/ms189461(v=SQL.110).aspx

您可能会发现示例C最有用,虽然看起来您不想要PARTITION,但是您想要使用RANGE。

对于计算列,您需要这样的内容:

 SUM(ISNULL(Debit,0)+ISNULL(Credit,0)) 
       OVER(RANGE UNBOUNDED PRECEDING AND CURRENT ROW) AS RunningTotal

这将导致查询类似于:

SELECT T1.[RefDate], T1.[TransId], T1.[BaseRef], T1.[LineMemo], T3.[Dscription], T1.[Debit], T1.[Credit], T4.[AcctName],
    SUM(ISNULL(Debit,0)+ISNULL(Credit,0)) 
               OVER(RANGE UNBOUNDED PRECEDING AND CURRENT ROW) AS RunningTotal
            FROM OJDT T0
            right JOIN JDT1 T1 ON T0.TransId = T1.TransId
            left JOIN OPCH T2 ON T0.TransId = T2.TransId
            left JOIN PCH1 T3 ON T3.DocEntry = T2.DocEntry
            left JOIN OACT T4 ON T1.Account = T4.AcctCode
            WHERE T4.[AcctCode] = [%0] AND
            T1.[RefDate] BETWEEN [%1] AND [%2]