SQL 列和与差

SQL column sum and difference

我的table,我想单栏创建三栏,现转载

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

我的table,我想单栏创建三栏,现转载

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" sums "receiv" sums 和 Type = "payment" sums 将添加到 "remainder" 列。

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

运行 total 在其他具有分析功能的数据库中更容易。在 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