perf(accounting): single query with window functions instead of two separate scans

This commit is contained in:
yumoqing 2026-07-17 15:17:56 +08:00
parent 6986ade835
commit 1152e02a27

View File

@ -19,7 +19,10 @@ ns = {
async with get_sor_context(request._run_ns, 'accounting') as sor: async with get_sor_context(request._run_ns, 'accounting') as sor:
sql = """select d.acc_date, d.acc_timestamp, d.acc_dir, d.summary, sql = """select d.acc_date, d.acc_timestamp, d.acc_dir, d.summary,
d.amount, d.balance, s.name as subject_name d.amount, d.balance, s.name as subject_name,
count(*) over() as _total,
coalesce(sum(case when d.acc_dir = '1' then d.amount else 0 end) over(), 0) as _debit,
coalesce(sum(case when d.acc_dir = '0' then d.amount else 0 end) over(), 0) as _credit
from acc_detail d from acc_detail d
join account a on d.accountid = a.id COLLATE utf8mb4_unicode_ci join account a on d.accountid = a.id COLLATE utf8mb4_unicode_ci
left join subject s on a.subjectid = s.id COLLATE utf8mb4_unicode_ci left join subject s on a.subjectid = s.id COLLATE utf8mb4_unicode_ci
@ -28,30 +31,23 @@ where a.orgid = ${orgid}$
and d.acc_date <= ${end_date}$""" and d.acc_date <= ${end_date}$"""
rows = await sor.sqlExe(sql, ns) rows = await sor.sqlExe(sql, ns)
stats_ns = { if not isinstance(rows, list):
'orgid': userorgid, data_rows = rows.rows
'start_date': start_date, total = rows.total
'end_date': end_date, first = data_rows[0] if data_rows else None
'sort': '1' else:
} data_rows = rows
stats_sql = """select total = len(rows)
count(*) as total_count, first = data_rows[0] if data_rows else None
coalesce(sum(case when d.acc_dir = '1' then d.amount else 0 end), 0) as debit_sum,
coalesce(sum(case when d.acc_dir = '0' then d.amount else 0 end), 0) as credit_sum
from acc_detail d
join account a on d.accountid = a.id COLLATE utf8mb4_unicode_ci
where a.orgid = ${orgid}$
and d.acc_date >= ${start_date}$
and d.acc_date <= ${end_date}$"""
stats_recs = await sor.sqlExe(stats_sql, stats_ns)
stats = { stats = {
'total_count': int(stats_recs[0].total_count) if stats_recs else 0, 'total_count': total,
'debit_sum': float(stats_recs[0].debit_sum) if stats_recs else 0, 'debit_sum': round(float(first._debit), 4) if first else 0,
'credit_sum': float(stats_recs[0].credit_sum) if stats_recs else 0 'credit_sum': round(float(first._credit), 4) if first else 0
} }
result = { result = {
'total': rows.total if not isinstance(rows, list) else len(rows), 'total': total,
'rows': rows.rows if not isinstance(rows, list) else rows, 'rows': data_rows,
'stats': stats 'stats': stats
} }
return json.dumps(result, ensure_ascii=False, default=str) return json.dumps(result, ensure_ascii=False, default=str)