SQL列的总和与差异

时间:2016-11-04 15:26:38

标签: sql delphi-7

我的表格,我想在单列中创建三列,现在重新打印。

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”总和“receiv”总和,Type =“payment”总和将被添加到“余额”列。

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

1 个答案:

答案 0 :(得分: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