2014-10-09 51 views
0

計算我有這個疑問:的MySQL從相同的值

SELECT `item_code`, 
     `q_rr`, 
     `q_srs`, 
     @running_bal := @running_bal + (`q_rr` - `q_srs`) as `Balance` 
FROM records, (SELECT @running_bal := 0) tempName 
order by 
     records.item_code, 
     records.date 

導致是:

item_code | q_rr | q_srs | balance 
-------------------------------------------- 
0F02206A  2  0   2 
BR00113D  3  0   5 
BR00114D  10  0   15 
BR00114D  0  1   14 
BR00114D  0  1   13 
BR00115D  20  0   33 
BR00115D  0  1   32 
BR00115D  0  1   31 

需要幫助,使結果計算差額,如果q_rr(+)和q_srs( - )並計算每個item_code。

item_code | q_rr | q_srs | balance 
-------------------------------------------- 
0F02206A  2  0   2 
BR00113D  3  0   3 
BR00114D  10  0   10 
BR00114D  0  1   9 
BR00114D  0  1   8 
BR00115D  20  0   20 
BR00115D  0  1   19 
BR00115D  0  1   18 
+0

你能幫助創造sqlfiddle和共享的鏈接? – 2014-10-09 09:24:44

回答

0

我添加@code變量來跟蹤item_code變化:

SELECT 
    r.item_code, 
    r.q_rr, 
    r.q_srs, 
    @running_bal := IF(@code = r.item_code, @running_bal, 0) + (r.q_rr - r.q_srs) as Balance, 
    @code := r.item_code AS dummy 
FROM 
    records r 
CROSS JOIN 
    (SELECT @running_bal := 0, @code := '') tempName 
ORDER BY 
    r.item_code, 
    r.date 

SQL小提琴:http://sqlfiddle.com/#!2/04ef2b/11

你可以把這個作爲子查詢中的另一個消除dummy欄中選擇:

SELECT item_code, q_rr, q_srs, Balance 
FROM (
    -- there put first query 
) r 

SQL小提琴:http://sqlfiddle.com/#!2/04ef2b/12

0

試試這個:

SELECT `item_code`, 
     `id`, 
     `type`, 
     @running_bal := case when type = 0 then id 
     else @running_bal + (`id` - `type`) end as `Balance` 
FROM supportContacts, (SELECT @running_bal := 0) tempName 
order by 
     supportContacts.item_code 

SQL FIDDLE