跳至主要內容
查询进阶(对比 JS reduce/groupBy)

1. 聚合函数(≈ JS reduce)

// 前端:统计订单数据
const orders = [
    { id: 1, customer: '小明', amount: 100, status: 'completed' },
    { id: 2, customer: '小红', amount: 200, status: 'completed' },
    { id: 3, customer: '小刚', amount: 150, status: 'pending' },
];

const total = orders.reduce((s, o) => s + o.amount, 0);           // 总金额
const count = orders.length;                                        // 订单数
const avg = total / count;                                          // 平均金额
const max = Math.max(...orders.map(o => o.amount));                 // 最大金额
const min = Math.min(...orders.map(o => o.amount));                 // 最小金额

Mr.Ding大约 3 分钟mysql查询聚合GROUP BY前端转后端