复杂查询以获得每天的总余额

时间:2014-03-26 21:46:24

标签: mysql sql

我正在尝试跟踪查询以获取条形图中使用的总余额和日期,并且其工作但是如果有2个条目使用该日期则返回相同日期的2个条目,但我想将这些日期分组为1个日期......

mysql查询...

SELECT dnt, 
@running_bal := @running_bal + (`Credit` - `Debit`)  as `Balance`
FROM transactions, (SELECT @running_bal := 0) tempName
ORDER BY dnt ASC

示例结果......

+----------------------+-----------+
|         dnt          |  Balance  |
+----------------------+-----------+
| 2014-03-06 10:30:00  | 28350.00  |
| 2014-03-06 10:30:00  | 29295.00  |
| 2014-03-13 09:30:00  | 57645.00  |
| 2014-03-13 09:30:00  | 85995.00  |
| 2014-03-17 09:30:00  | 114345.00 |
| 2014-03-20 09:30:00  | 134190.00 |
| 2014-03-26 20:02:30  | 133690.00 |
+----------------------+-----------+

1 个答案:

答案 0 :(得分:1)

这样的事情:

SELECT dnt, 
   @running_bal := @running_bal + `Balance` as `Balance`
FROM 
  (SELECT dnt, SUM(Credit) - SUM(Debit) as `Balance` FROM transactions GROUP BY dnt) tmp,
  (SELECT @running_bal := 0) tempName
ORDER BY dnt ASC