2012-11-16 81 views
0

我有一个小型的php程序,用于显示每个员工的所有待处理数量,但我在acc_code中总计出现了一些问题。在MySQL中按组计算总数

我已经解释了下面的系统。每个工作人员都分配了一个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 

任何帮助将不胜感激

回答

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 

请注意,我没有检查您的查询。我刚刚添加了我认为你错过的东西。 当你想要获得团队成果时,你需要什么样的员工姓名?

+0

我需要显示每个acc_code的个人记录,这是我在我的代码中完成的,我只需要每个acc_code的总数。分组bt acc_code不起作用。我需要将每个acc_c的pending.amount总结为几个月。 – LiveEn

+0

为什么不用预期的结果表编辑你的问题(你想出现的方式,手动编写),因为我不明白你真正需要什么。 –

+0

我已经添加了预期的输出。谢谢 – LiveEn

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 
+0

由staff.acc_code分组不显示个人记录。需要个人记录(如我的代码)和每个acc_code的总值 – LiveEn

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