我有这个查询,我写的是为了获得期初余额和余额,但它没有计算CrAmount
。我不确定我是否可以提供表格结构和数据,因为如果有人能够发现这个问题,那么这个结构和数据太大而且太复杂了。
;WITH CTE AS (
SELECT
[Master].[TransactionCode], [Master].[TransactionDate], SUM(DrAmount) [DrAmount], SUM(CrAmount) [CrAmount]
FROM
[FICO].[tbl_TransactionDetail] [Detail], [FICO].[tbl_TransactionMaster] [Master]
--WHERE [VoucherDate] BETWEEN CAST('Dec 01 2017 12:00AM' AS DATE) AND CAST('Dec 30 2017 12:00AM' AS DATE)
WHERE
[Master].[ID] = [Detail].[TransactionCode]
GROUP BY [Detail].[ID], [Master].[TransactionCode], [Master].[TransactionDate]
)
SELECT TransactionCode, [TransactionDate], D.DrAmount, D.CrAmount, D.Amount, D.Amount-ISNULL(D.DrAmount,D.CrAmount) [Opening]
FROM(
SELECT *,
SUM(ISNULL(DrAmount, 0)+ISNULL(CrAmount, 0)) OVER (ORDER BY TransactionCode
) as Amount
FROM CTE
)D
WHERE D.[TransactionDate] BETWEEN CAST('Mar 26 2018 12:00AM' AS DATE) AND CAST('Mar 30 2018 12:00AM' AS DATE)
输出就是这个。如果给出DrAmount,它将从Amount中减去它并显示Opening Balance。金额是根据数据库中的先前条目计算的。
TransactionCode TransactionDate DrAmount CrAmount Amount Opening
-------------------------------------------------- ----------------------- --------------------------------------- --------------------------------------- --------------------------------------- ---------------------------------------
CPV--43---18 2018-03-26 00:00:00.000 25000.0000000 0.0000000 98666164.0000000 98641164.0000000
CPV--43---18 2018-03-26 00:00:00.000 0.0000000 28700.0000000 98666164.0000000 98666164.0000000
CPV--43---18 2018-03-26 00:00:00.000 1500.0000000 0.0000000 98666164.0000000 98664664.0000000
CPV--43---18 2018-03-26 00:00:00.000 2200.0000000 0.0000000 98666164.0000000 98663964.0000000
CPV--44---18 2018-03-27 00:00:00.000 2300.0000000 0.0000000 98670764.0000000 98668464.0000000
CPV--44---18 2018-03-27 00:00:00.000 0.0000000 2300.0000000 98670764.0000000 98670764.0000000
答案 0 :(得分:0)
也许你应该像这样处理它:
DR = case when SUM(DR-CR) >=0 then SUM(DR-CR) else 0 end
CR = case when SUM(CR-DR) >=0 then SUM(CR-DR) else 0 end
以下是如何应用这个:
--put in your dates here
declare @start date = '20180301'
, @end date = '20180331'
select transactionid
,DR = case when SUM(DR-CR) >=0 then SUM(DR-CR) else 0 end
,CR = case when SUM(CR-DR) >=0 then SUM(CR-DR) else 0 end
from detail d
join header h on d.id=h.id
where trandate <= @start
group by transactionID
union all
select transactionid, DR,CR
from detail
join header h on d.id=h.id
where transdate between @start and @end