在SQL Server中生成基本分类帐报告

时间:2012-03-06 08:29:13

标签: sql-server-2005 tsql

我有一个样本帐户交易表,如下所示:

VchNo   TranDate    Credits     Debits
PR1    07 Dec 2011  10000.50      0.00
PI1    13 Dec 2011  26000.00      0.00
PI2    14 Dec 2011  15841.50      0.00
PR2    15 Dec 2011  9845.25       0.00
PL1    31 Dec 2011     0.00   58741.25
PJ3    02 Jan 2012     0.00    1021.00

我知道此帐户的期初余额

Opening Balance: 99825.00

我希望通过显示上述每笔交易的期初和期末余额来生成这样的基本分类账报表,如下所示:

VchNo  TranDate     Opening       Credits    Debits   Closing
PR1   07 Dec 2011   99825.00    10000.50      0.00  109825.50
PI1   13 Dec 2011   109825.50   26000.00      0.00  135825.50
PI2   14 Dec 2011   135825.50   15841.50      0.00  151667.00
PR2   15 Dec 2011   151667.00   9845.25       0.00  161512.25
PL1   31 Dec 2011   161512.25      0.00   58741.25  102771.00
PJ3   02 Jan 2012   102771.00      0.00    1021.00  101750.00

在上表中,结束=开盘+积分 - 借记
今天结束是第二天(后一天)的开幕。 在101750.00获得期末余额(参见VchNo PJ3的最后一栏)。

我附上了样本报告格式,以便快速参考Ledger Report  是否可以使用SINGLE SQL查询实现此目的?

1 个答案:

答案 0 :(得分:2)

这应该有效:

CREATE TABLE #Data
(vchno NVARCHAR(6)
,trandate DATETIME
,credits DECIMAL(18,3)
,debits DECIMAL(18,3)
,opening DECIMAL(18,3)
)
INSERT INTO #Data
SELECT 'PR1'as vchno,'07 Dec 2011'as trandate,10000.50 as credits,0.00 as debits,99825 AS opening
UNION ALL SELECT 'PI1' ,'13 Dec 2011' ,  26000.00 ,  0.00,99825  
UNION ALL SELECT 'PI2','14 Dec 2011',  15841.50,  0.00 ,99825
UNION ALL SELECT 'PR2','15 Dec 2011',  9845.25 ,  0.00 ,99825
UNION ALL SELECT 'PL1','31 Dec 2011', 0.00 ,  58741.25 ,99825
UNION ALL SELECT 'PJ3','02 Jan 2012', 0.00,1021.00 ,99825

;With ledger AS
(
SELECT vchno
,trandate
,opening
,credits
,debits
,opening + credits - debits AS closing
,row_number() OVER (ORDER BY trandate) AS row
FROM #data
)
SELECT
l1.vchno
,l1.trandate
,MAX(l1.opening) + ISNULL(SUM(l2.credits),0) - ISNULL(SUM(l2.debits),0) as opening
,MAX(l1.credits) AS issues
,MAX(l1.debits) AS Receips
,MAX(l1.opening) + ISNULL(SUM(l2.credits),0) - ISNULL(SUM(l2.debits),0) + MAX(l1.credits) - MAX(l1.debits) as closing
FROM ledger l1 
LEFT OUTER JOIN ledger l2 on l2.row < l1.row
GROUP BY
l1.vchno
,l1.trandate