我有 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 的任何线索,它将向我显示在后代模式下按交易日期排序的正确余额?
非常感谢。
编辑:考虑 2 个可能的解决方案
当您在 2 个交易中具有相同的日期时会产生问题,所以这就是我要做的:
- 将日期和时间保存到“日期”列中。这样就不会有2个确切的日期。
或者
- 创建一个“优先级”列并为每条记录设置优先级。因此,如果我发现日期已经存在并且它的优先级 = 1,那么当前的优先级将为 2。
你怎么看?