我的数据库中有一个类似于以下内容的表
+----+----+----+---------------------+
| id | a | b | date_created |
+----+----+----+---------------------+
| 1 | 22 | 33 | 2014-07-31 14:38:17 |
| 2 | 11 | 9 | 2014-07-30 14:40:19 |
| 3 | 8 | 4 | 2014-07-29 14:40:34 |
+----+----+----+---------------------+
我正在尝试编写一个从每个sum(b)
中减去a
的查询。但是,b
中包含的sum(b)
值应该只是那些早于(或同时)a
的值。换句话说,查询返回的结果应该是下面显示的结果
22 - (33 + 9 + 4)
11 - (9 + 4)
8 - (4)
是否可以在单个查询中计算出来?
答案 0 :(得分:4)
select id, a, a - (select sum(b)
from My_TABLE T2
where T2.date_created <= T1.date_created)
from MY_TABLE T1;
答案 1 :(得分:2)
这样的事情应该有效:
select t1.a - ifnull( sum(t2.b), 0)
from myTable t1
left outer join myTable t2 on t2.date_created <= t1.date_created
group by t1.a
请注意,该表已连接到自身以访问两组不同的信息。
编辑:
我想你可能想按照date_created分组:
select t1.date_created, t1.a - ifnull( sum(t2.b), 0)
from myTable t1
left outer join myTable t2 on t2.date_created <= t1.date_created
group by t1.date_created, t1.a
答案 2 :(得分:1)
另一种选择
<强> SQL Fiddle Example 强>
SELECT
id,
a - (@total := @total + b) as Total
FROM
(SELECT *, @total:=0
FROM my_table
ORDER BY date_created asc) AS Base
答案 3 :(得分:1)
SELECT x.*
, x.a - SUM(y.b)
FROM my_table x
JOIN my_table y
ON y.date_created <= x.date_created
GROUP
BY x.id;