2016-11-04 4 views
3

내 테이블은 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 

내 테이블에서 3 열을 하나의 열로 만들고 지금 다시 인쇄하고 싶습니다.

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"sum "receiv"sums 및 Type = "payment"합계가 "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 
+0

? 보이는 분석 함수는 도움이 될 수 있지만 구문은 DB에 따라 달라질 수 있습니다. – Kacper

+0

나는 MySQL 데이터베이스를 사용하고있다. –

답변

1

분석 기능이있는 다른 데이터베이스의 누적 합계가 더 쉽습니다. MySQL에서는 상호 연관된 하위 쿼리를 사용하여이를 수행 할 수 있습니다.

사용 어떤 DB
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