如何计算当前周期日均余额?求正确MySQL查询语句
计算周期日均余额的MySQL查询方案
我有以下交易数据,需要计算当前周期日均余额(目标值为$1,595.49)。尝试过均值、中位数、众数以及手动求和除以总行数的方法,结果都不符合预期。
fd tr_type amount date balance 8 credit 789.81 2/2/2024 789.81 8 credit 529.98 2/15/2024 1319.79 8 debit 29 2/15/2024 1290.79 8 debit 95.99 2/20/2024 1194.8 8 credit 1000 2/21/2024 2194.8 8 credit 494.12 2/22/2024 2688.92 8 debit 10 2/22/2024 2678.92 8 debit 1405 2/22/2024 1273.92 8 debit 15 2/23/2024 1258.92 8 credit 571 2/27/2024 1829.92 8 credit 533.8 2/29/2024 1258.92 8 credit 0.05 2/29/2024 1829.92 8 debit 123.07 3/6/2024 2240.7 8 debit 186.58 3/6/2024 2054.12 8 credit 516.4 3/7/2024 2570.52 8 debit 138.53 3/7/2024 2431.99 8 debit 510.23 3/8/2024 1921.76
尝试每日余额乘以间隔天数求和,再除以周期总天数的方法,结果接近正确值(仅差0.02)。需要能直接得到$1,595.49的MySQL查询语句,现有查询仅计算第一行日期差,无法满足需求:
SELECT date1, fd, balance, CASE WHEN next_date IS NOT NULL THEN DATEDIFF(next_date, date1) * amount ELSE 1* amount END AS adjusted_amount FROM ( SELECT date1, transaction_type, amount, fd, (SELECT SUM( CASE WHEN t.transaction_type = 'credit' THEN t.amount WHEN t.transaction_type = 'debit' THEN -t.amount ELSE 0 END ) FROM transactions t WHERE fd='8' AND t.date1 <= transactions.date1) AS balance , LEAD(date1) OVER (PARTITION BY fd ORDER BY date1 ASC) AS next_date FROM transactions WHERE fd='8' ) subquery ORDER BY date1 ASC;
正确的MySQL查询语句
-- 计算fd=8的周期日均余额,目标值$1,595.49 SELECT fd, ROUND(SUM(balance * days_active) / total_days, 2) AS average_daily_balance FROM ( SELECT fd, date, balance, -- 计算当前余额的持续天数:下一笔交易日期 - 当前交易日期;最后一笔用周期结束日(2024-03-08) DATEDIFF( COALESCE(LEAD(date) OVER (PARTITION BY fd ORDER BY date ASC), '2024-03-08'), date ) AS days_active, -- 计算周期总天数:从第一笔交易到最后一笔交易的总天数(含首尾) (SELECT DATEDIFF(MAX(date), MIN(date)) + 1 FROM transactions WHERE fd='8') AS total_days FROM transactions WHERE fd='8' ) AS balance_periods GROUP BY fd;
关键修正点
- 用
LEAD函数自动获取每笔交易的下一笔交易日期,解决了原查询仅处理第一行日期差的问题。 - 用
COALESCE处理最后一笔交易的边界情况,确保余额持续到周期结束日。 - 基于交易数据自动计算周期总天数,避免手动输入误差。
- 最终结果保留两位小数,与目标值格式完全匹配。
内容的提问来源于stack exchange,提问作者waqasss
相关产品推荐
相关产品推荐

