我有2个SQL表
unit_transaction unit_detail_transactions
(这里的表架构:http://sqlfiddle.com/#!3/e3204/2)
我需要的是执行SQL查询以生成包含余额的表。现在我有这个SQL查询但它没有正常工作,因为当我有2个同一日期的交易时,余额没有正确计算。
SELECT
ft.transactionid,
ft.date,
ft.reference,
ft.transactiontype,
CASE ftd.isdebit WHEN 1 THEN MAX(ftd.debitaccountid) ELSE MAX(ftd.creditaccountid) END as financialaccountname,
CAST(COUNT(0) as tinyint) as totaldetailrecords,
ftd.isdebit,
SUM(ftd.amount) as amount,
balance.amount as balance
FROM unit_transaction_details ftd
JOIN unit_transactions ft ON ft.transactionid = ftd.transactionid
JOIN
(
SELECT DISTINCT
a.transactionid,
SUM(CASE b.isdebit WHEN 1 THEN b.amount ELSE -ABS(b.amount) END) as amount
--SUM(b.debit-b.credit) as amount
FROM unit_transaction_details a
JOIN unit_transactions ft ON ft.transactionid = a.transactionid
CROSS JOIN unit_transaction_details b
JOIN unit_transactions ft2 ON ft2.transactionid = b.transactionid
WHERE (ft2.date <= ft.date)
AND ft.unitid = 1
AND ft2.unitid = 1
AND a.masterentity = 'CONDO-A'
GROUP BY a.transactionid,a.amount
) balance ON balance.transactionid = ft.transactionid
WHERE
ft.unitid = 1
AND ftd.isactive = 1
GROUP BY
ft.transactionid,
ft.date,
ft.reference,
ft.transactiontype,
ftd.isdebit,
balance.amount
ORDER BY ft.date DESC
查询结果如下:
有关如何执行正确的SQL的任何线索,这些SQL将以后代模式显示按事务日期排序的正确余额?
非常感谢。
编辑:认为2个可能的解决方案
当你在2个交易中拥有相同的日期时会产生问题,所以这就是我要做的事情:
OR
您怎么看?
答案 0 :(得分:4)
有两种方法可以进行运行总和。我将在一个更简单的表上显示语法,为您提供一个想法。
某些数据库(例如Oracle,PostgreSQL,SQL Server 2012,Teradata,DB2)直接支持累积总和。为此,您可以使用以下功能:
select sum(<val>) over (partition by <column> order by <ordering column>)
from t
这是一个Windows函数,它将计算由每个记录组记录的运行总和。总和的顺序是。
唉,许多数据库不支持此功能,因此您需要在数据库中的单个SELECT查询中执行自连接:
select t.column, sum(tprev.<val>) as cumsum
from t left join
t tprev
where t.<column> = tprev.<column> and
t.<ordering column> >= tprev.<ordering column>
group by t.column
还可以创建另一个表并使用游标分配累积总和,或者在应用程序级别进行总和。