在MySQL中按组计算总数

时间:2012-11-16 15:25:28

标签: mysql sql

我有一个小的php程序,用于显示每个工作人员的所有待处理金额,但是我在累计acc_code的组值方面遇到了一些问题。

我已经解释了下面的系统。每位员工都被分配了一个acc_code。每个帐户代码都有40-50名员工

例如:

admission  name   months  acc_code
==================================
001        test1  3       10A
002        test2  5       10A
006        test3  7       15B
008        test4  1       15A
011        test5  2       16C
051        test6  3       16A
012        test7  3       16A

预期产出:

 admission  name   months  acc_code
    ==================================
    001        test1  3       10A
    002        test2  5       10A
                    Total    USD 1000

    006        test3  7       15B
                    Total    USD 1800

    008        test4  1       15A
                    Total    USD 800

    011        test5  2       16C
                    Total    USD 1600

    051        test6  3       16A
    012        test7  3       16A
                     Total    USD 2700

每位员工都有一定的金额。我需要获取每个acc_code的总待处理金额

以下是我编写的代码,但我不确定如何获得每个ac_code的总计

select
  (period_diff(date_format(now(), '%Y%m'),
  date_format(month, '%Y%m'))) as months,
  pending.amount,
  pending.admission_numb,
  pending.month,
  staff.full_name,
  staff.acc_code
from
  pending join staff 
  on pending.admission_numb = staff.admission 
group by
  admission
order by
  staff.acc_code asc

任何帮助将不胜感激

3 个答案:

答案 0 :(得分:1)

select
  staff.acc_code,
  SUM(pending.amount) pending_amount
from
  pending join staff 
  on pending.admission_numb = staff.admission 
group by
  staff.acc_code
order by
  staff.acc_code asc

答案 1 :(得分:0)

您需要GROUP BY acc_code和SUM月份。像这样:

select SUM ((period_diff(date_format(now(), '%Y%m'), date_format(month, '%Y%m'))) as months),
pending.amount, pending.admission_numb, pending.month, staff.full_name, staff.acc_code
from pending join staff 
on pending.admission_numb = staff.admission 
group by staff.acc_code order by staff.acc_code asc

请注意,我没有检查您的查询。我刚刚添加了我认为你遗失的东西。 当你试图为小组获得结果时,你需要员工的名字是什么?

答案 2 :(得分:0)

以下是获取acc_code总计的方法。

select
  (period_diff(date_format(now(), '%Y%m'),
  date_format(month, '%Y%m'))) as months,
  pending.amount,
  pending.admission_numb,
  pending.month,
  staff.full_name,
  staff.acc_code,
  (SELECT SUM(pending.amount) FROM pending p join staff s on p.admission_numb = s.admission WHERE p.acc_code = staff.acc_code) acc_code_total_pending
from
  pending join staff 
  on pending.admission_numb = staff.admission 
group by
  admission
order by
  staff.acc_code asc