Search code examples
sqldelphi-7

SQL column sum and difference


my table, I want to create three columns in single-column, reprinted now.

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

my table, I want to create three columns in single-column, reprinted now.

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

-- The following query for the sql code? Type = "Paypal, credit, Cash" sums "receiv" sums and Type = "payment" sums will be added to the "remainder" column.

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

Solution

  • Running total is easier in other databases which have analytical functions. In MySQL, you can do this with a correlated sub-query.

    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