2012-11-16 119 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