perf(accounting): single query with window functions instead of two separate scans
This commit is contained in:
parent
6986ade835
commit
1152e02a27
@ -19,7 +19,10 @@ ns = {
|
||||
|
||||
async with get_sor_context(request._run_ns, 'accounting') as sor:
|
||||
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
|
||||
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
|
||||
@ -28,30 +31,23 @@ where a.orgid = ${orgid}$
|
||||
and d.acc_date <= ${end_date}$"""
|
||||
rows = await sor.sqlExe(sql, ns)
|
||||
|
||||
stats_ns = {
|
||||
'orgid': userorgid,
|
||||
'start_date': start_date,
|
||||
'end_date': end_date,
|
||||
'sort': '1'
|
||||
}
|
||||
stats_sql = """select
|
||||
count(*) as total_count,
|
||||
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)
|
||||
if not isinstance(rows, list):
|
||||
data_rows = rows.rows
|
||||
total = rows.total
|
||||
first = data_rows[0] if data_rows else None
|
||||
else:
|
||||
data_rows = rows
|
||||
total = len(rows)
|
||||
first = data_rows[0] if data_rows else None
|
||||
|
||||
stats = {
|
||||
'total_count': int(stats_recs[0].total_count) if stats_recs else 0,
|
||||
'debit_sum': float(stats_recs[0].debit_sum) if stats_recs else 0,
|
||||
'credit_sum': float(stats_recs[0].credit_sum) if stats_recs else 0
|
||||
'total_count': total,
|
||||
'debit_sum': round(float(first._debit), 4) if first else 0,
|
||||
'credit_sum': round(float(first._credit), 4) if first else 0
|
||||
}
|
||||
result = {
|
||||
'total': rows.total if not isinstance(rows, list) else len(rows),
|
||||
'rows': rows.rows if not isinstance(rows, list) else rows,
|
||||
'total': total,
|
||||
'rows': data_rows,
|
||||
'stats': stats
|
||||
}
|
||||
return json.dumps(result, ensure_ascii=False, default=str)
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user