我有这个问题:
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 :(得分: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
答案 1 :(得分: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