SQL查询余额

时间:2013-06-26 06:27:38

标签: mysql sql

我有这样的查询...

+-----+------------+--------+---------+---------+
| seq | fld_Date   | CBU_IN | CBU_OUT | Balance |
+-----+------------+--------+---------+---------+
|  41 | 2012-10-08 | 150.00 | 0.00    | 150.00  |
|  42 | 2012-10-15 | 50.00  | 0.00    | 200.00  |
|  43 | 2012-10-22 | 50.00  | 0.00    | 250.00  |
|  44 | 2012-10-29 | 50.00  | 0.00    | 300.00  |
|  45 | 2012-11-05 | 50.00  | 0.00    | 350.00  |
|  46 | 2012-11-12 | 50.00  | 0.00    | 400.00  |
|  47 | 2012-11-19 | 50.00  | 0.00    | 450.00  |
+-----+------------+--------+---------+---------+

所有我想要的是这种输出,其中下一行日期来自fld_Date的下一行。

+-----+------------+---------------+--------+---------+---------+
| seq | fld_Date   | next_row_date | CBU_IN | CBU_OUT | Balance |
+-----+------------+---------------+--------+---------+---------+
|  41 | 2012-10-08 | 2012-10-15    | 150.00 | 0.00    | 150.00  |
|  42 | 2012-10-15 | 2012-10-22    | 50.00  | 0.00    | 200.00  |
|  43 | 2012-10-22 | 2012-10-25    | 50.00  | 0.00    | 250.00  |
|  44 | 2012-10-25 | 2012-11-05    | 50.00  | 0.00    | 300.00  |
|  45 | 2012-11-05 | 2012-11-12    | 50.00  | 0.00    | 350.00  |
|  46 | 2012-11-12 | 2012-11-16    | 50.00  | 0.00    | 400.00  |
|  47 | 2012-11-16 | 2012-11-26    | 50.00  | 0.00    | 450.00  |
+-----+------------+---------------+--------+---------+---------+

你能帮我解决这个......谢谢...

这是我的查询...

 SELECT 
        lms_savings.seq,
        lms_savings.fld_Date,
        FORMAT(lms_savings.CBU,2)AS CBU_IN,
        FORMAT(lms_savings.CBU_OUT,2)AS CBU_OUT,        
    FORMAT(@Balance := @Balance + lms_savings.CBU - lms_savings.CBU_OUT,2) AS Balance
FROM lms_savings, (SELECT @Balance := 0) AS variableInit

2 个答案:

答案 0 :(得分:0)

将您的查询代替“您的查询”

 select a.seq, a.fld_Date,b.fld_Date as next_row_date, 
        a.CBU_IN,a.CBU_OUT,a.Balance 
 from ( your query ) a left outer join (your query) b
 on a.seq = b.seq-1

答案 1 :(得分:0)

select a.seq, a.fld_Date, b.fld_Date as next_row_date , a.CBU_IN, a.CBU_OUT, a.Balance   
from table_name a, table_name b
where a.seq = b.seq+1