我应该如何计算我的期初和期末余额

时间:2018-02-16 11:36:08

标签: sql sql-server

我正在研究交易数据我每天在一个表数据中有两个表 第一张表: -

gl_cde  txn_dt  txn_id  amount
2104    20140429    10  12750.00
2104    20140429    12  1263.89
2104    20140429    14  793.33
2104    20140429    16  12833.33

第二张表

txn_dte gl_cde  balance
20140424    2104    12791.67  ---Opening balance
20140429    2104    40432.22  ---closing balance

我正在寻找结果

Id  gl_cde  Date    Result
1   2104    20140424    12791.67 ---Opening balance
2   2104    20140429    12750
3   2104    20140429    1263.89
4   2104    20140429    793.33
5   2104    20140429    12833.33
6   2104    20140429    40432.22 ---closing balance

实际上,我正在寻找我的第一张表中的期初余额+总和(金额)等于我的期末余额。

我没有得到如何在sql server 2012中为此编写查询这只是一个例子bcz对于一个gl_cde我有多个日期并且在第一个表中有多个gl_cde

2 个答案:

答案 0 :(得分:0)

您可以使用union allorder by

select row_number() over (partition by gl_cde order by ordering, date),
       gl_cde, date, amount
from ((select gl_cde, Date, Amount, 2 as ordering from t1) union all
      (select gl_cde, Date, balance,
              row_number() over (partition by gl_cde order by date) * 2 - 1
       from t2
      )
     ) tt
order by gl_cde, ordering, date

答案 1 :(得分:0)

我不是说这个特别漂亮, 假设 第二个数据集中只有2条记录(包括您的期初余额和期末余额)。如果不是这种情况,您需要使用更多方案更新您的帖子。

WITH VTE1 AS (
    SELECT gl_cde, CONVERT(date, txn_dt) AS txn_dt, txn_id, amount
    FROM (VALUES(2104,'20140429',10,12750.00),
                (2104,'20140429',12,1263.89 ),
                (2104,'20140429',14,793.33  ),
                (2104,'20140429',16,12833.33)) V(gl_cde, txn_dt, txn_id, amount)),
VTE2 AS (
    SELECT CONVERT(date,txn_dte) AS txn_dte, gl_cde, balance
    FROM (VALUES('20140424',2104,12791.67),
                ('20140429',2104,40432.22)) V(txn_dte, gl_cde, balance)),
Combined AS(
    SELECT gl_cde,
           txn_dt,
           amount AS Result,
           txn_id,
           'Transaction' AS DataType
    FROM VTE1
    UNION ALL
    SELECT gl_cde, txn_dte, balance AS result,
           ROW_NUMBER() OVER (ORDER BY txn_dte) * -1 AS Txn_id,
          'Balance' AS DataType
    FROM VTE2)
SELECT ROW_NUMBER() OVER (ORDER BY C.txn_dt, CASE txn_id WHEN -1 THEN 'A' WHEN -2 THEN 'C' ELSE 'B' END, txn_id) AS Id,
       gl_cde,
       txn_dt AS [Date],
       Result
FROM Combined C
ORDER BY C.txn_dt, 
         CASE txn_id WHEN -1 THEN 'A' WHEN -2 THEN 'C' ELSE 'B' END,
         txn_id;

我这里没有在数据中包含任何分区,因为我们只有一个帐户的数据。您需要使用相应的列添加PARTITION BY子句。