2014-10-15 2 views
1

에서 여러 행의 양의 합을 받고이 내 테이블 (invoice_payments는) :SQL : 하나의 테이블

invoice_payments table

나는 특정 조건 금액의 합으로 invoice_id별로 그룹화 행을 싶어. 내 SQL 쿼리 :이 결과를 얻고있다

select invoice_id, (select sum(invoice_payments.amount) from invoice_payments where 
invoice_payments.type!='Store') as total_paid, type from invoice_payments where 
invoice_payments.type!='Store' group by invoice_id 

는 :

My Query Result

이 잘못 볼 수 있듯이. 누군가 도움을 주거나 해결책을 제안하십시오. 나는 정말 어떤 대답을 주셔서 감사합니다. 위의 질의가 요구를 충족하는 경우

감사

+1

', total_paid 등의 합 (invoice_payments.amount를) invoice_id 선택 , invoice_payments에서 입력하십시오. invoice_payments.type! = '유형별로 그룹을 저장, invoice_id'? – Fougere

답변

1
select invoice_id, sum(invoice_payments.amount) 
from invoice_payments 
where invoice_payments.type!='Store' 
group by invoice_id. 

는 예상 출력을 게시하시기 바랍니다.

+0

이 검색어는 어떻게됩니까? 이 쿼리는 어떻게 수정합니까? 'invoice_payments.type! = '유형별로 그룹 저장'= total_payments에서 total_payments, sum (invoice_payments.amount)를 total_paid, sum (유형 = 'Store'다음에 invoice_payments.amount else 0 end) , invoice_id' – Maria

+0

@Maria. 위 qry에서 total_balance는 항상 0을 필요로합니다. – arunbabu

+0

왜 항상 0이 될까요? total_paid 및 total_balance가 모두 필요합니다. – Maria

1

당신은 sum 기능 내부 case 표현을 사용할 수 있습니다 : 나는 이유가 아닌 단지와 같은 일을하는, 두 번째 선택을하지 않는

SELECT invoice_id, 
     SUM(CASE WHEN type != 'Store' THEN amount ELSE 0 END) AS total_paid 
FROM  invoice_payments 
GORUP BY invoice_id 
+0

이 검색어는 어떻게됩니까? 이 쿼리는 어떻게 수정합니까? 'invoice_payments.type! = '유형별로 그룹 저장', total_payments에서 유형을 선택하십시오. invoice_id' – Maria