2016-11-04 59 views
3

我的表,我想在单列中创建三列,现转载。SQL列总和与

id  | date  | type | total 
------ | ------ | ------ | ----- 
1  | 01.10.2016| Paypal | 50 
2  | 03.10.2016| credit | 40 
3  | 05.10.2016| Cash | 50 
4  | 06.10.2016| payment| 100 
5  | 07.10.2016| Cash | 20 
6  | 15.10.2016| Skrill | 10 
7  | 18.10.2016| payment| 20 
8  | 19.10.2016| Paypal | 10 
9  | 19.10.2016| payment| 20 
10  | 22.10.2016| Cash | 40 
11  | 23.10.2016| Skrill | 10 

我的表,我想在单列中创建三列,现转载。

SELECT id,date,type,total 
(select (
sum(case when type="Paypal" then total else 0 end)+ 
sum(case when type="credit" then total else 0 end))+ 
sum(case when type="Cash" then total else 0 end)) as receiv, 
(Select( 
sum(case when type="payment" then total else 0 end)) AS payment, 
(Select sum(receiv -payment) FROM totals t2 
WHERE (t2.date <= t1.date) and (t2.id <= t1.id) order by t1.date) AS remainder 
FROM totals t1 
group by date, type 
order by id,date 

- 的SQL代码下面的查询? Type =“Paypal,credit,Cash”总计“收到”款项和Type =“付款”款项将被添加到“余额”栏中。

id  | date  | type | receiv| payment| remainder 
------ | ------ | ------ | ------| ------ | ------ 
1  | 01.10.2016| Paypal | 50 | 0  | 50 
2  | 03.10.2016| credit | 40 | 0  | 90 
3  | 05.10.2016| Cash | 50 | 0  | 140 
4  | 06.10.2016| payment| 0 | 100 | 40 
5  | 07.10.2016| Cash | 20 | 0  | 60 
6  | 15.10.2016| Skrill | 10 | 0  | 70 
7  | 18.10.2016| payment| 0 | 20  | 50 
8  | 19.10.2016| Paypal | 10 | 0  | 60 
9  | 19.10.2016| payment| 0 | 20  | 40 
10  | 22.10.2016| Cash | 40 | 0  | 80 
11  | 23.10.2016| Skrill | 10 | 0  | 90 
+0

你用什么数据库?它看起来分析功能可以帮助,但语法可能取决于数据库。 – Kacper

+0

我正在使用MySQL数据库 –

回答

1

在具有分析功能的其他数据库中,运行总计更容易。在MySQL中,您可以使用相关的子查询来完成此操作。

select id,dt,type, 
case when type <> 'payment' then total else 0 end receiv, 
case when type = 'payment' then total else 0 end payment, 
case when type <> 'payment' then total else 0 end 
- case when type = 'payment' then total else 0 end 
+ coalesce((select sum(case when type <> 'payment' then total else 0 end) 
        - sum(case when type = 'payment' then total else 0 end) 
      from yourtable where id < y.id),0) 
from yourtable y 

Sample Demo