开盘和平仓

时间:2018-03-19 07:35:27

标签: sql sql-server tsql

我正试图在查询中获得期初和期末余额。

这是我的查询

SELECT 
[Voucher].[TransactionCode] [VoucherNo], 
SUM([Detail].[DrAmount]) [DrAmount], SUM([Detail].[CrAmount]) [CrAmount]

FROM
[FICO].[tbl_TransactionMaster] [Voucher], [FICO].[tbl_TransactionDetail] [Detail]

WHERE  
[Detail].[TransactionCode] = [Voucher].[ID] 

GROUP BY [Voucher].[TransactionCode]

我得到的输出就是这个。

VoucherNo            DrAmount   CrAmount
FMS-CRV-1-1-Doc--18  12         12
FMS-CRV-2-1-Doc--18  999        999
FMS-CRV-3-1-Doc--18  18000      18000
FMS-JV-10-1-Doc--18  3000       3000
FMS-JV-1-1-Doc--18   99351      99351   

我期待的输出就像这样

VoucherNo            DrAmount   CrAmount   Amount
FMS-CRV-1-1-Doc--18  12         12         12
FMS-CRV-2-1-Doc--18  999        999        1011
FMS-CRV-3-1-Doc--18  18000      18000      19011
FMS-JV-10-1-Doc--18  3000       3000       22011
FMS-JV-1-1-Doc--18   99351      99351      121362

让我们说在此之前还有一个价值1000的凭证保存在数据库中,而不是它应该是这样的

VoucherNo            DrAmount   CrAmount   Amount
FMS-CRV-1-1-Doc--18  12         12         1012
FMS-CRV-2-1-Doc--18  999        999        2011
FMS-CRV-3-1-Doc--18  18000      18000      20011
FMS-JV-10-1-Doc--18  3000       3000       21011
FMS-JV-1-1-Doc--18   99351      99351      122362

1 个答案:

答案 0 :(得分:1)

首先使用正确的显式JOIN s(即INNER JOIN

WITH CTE AS (
    SELECT 
           td.TransactionCode, SUM(td.DrAmount) as DrAmount, SUM(td.CrAmount) as CrAmount
    FROM [FICO].[tbl_TransactionMaster] tm
    INNER JOIN [FICO].[tbl_TransactionDetail] td ON td.TransactionCode = tm.ID
    GROUP BY td.TransactionCode
)

SELECT *,
        SUM(CrAmount) OVER (ORDER BY TransactionCode 
                  ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as Amount
FROM CTE

至于所需的结果,您需要使用窗口函数与之前的金额相加。