SQL SUM amouts by distinct bill's numbers

Rytis

I have this query:

SELECT companys.name as pav, SUM(distinct bills.amout) - SUM(cheques.amount)AS 
amount FROM companys INNER JOIN bills ON companys.id   = bills.company LEFT  JOIN 
cheques ON bills.bill_nr = cheques.bill_nr GROUP BY companys.name

For example if I have 2 bills with amounts (1000 and 1000) and 2 cheques for first bill (100 and 200) and for second 1 cheque (800), I get result -100 instead of 900. This happens because it sums bill amount 1000 only one time because they are same, but I need to sum them of distinct bills.bill.nr. How to do that? Thank you!

Gordon Linoff

Your problem is that the checks are multiplying the billed amounts. A good solution is to aggregate everything before the join, so the numbers are all correct:

SELECT c.name as pav, (bamount - COALESCE(chamount, 0)) AS amount
FROM companys c INNER JOIN
     (SELECT b.company, SUM(b.amount) as bamount
      FROM bills b
      GROUP BY b.company
     ) b
     ON c.id = b.company LEFT JOIN
     (SELECT b.company, SUM(ch.amount) as chamount
      FROM bills b JOIN
           cheques ch
           ON b.bill_nr = ch.bill_nr
      GROUP BY b.company
     ) ch
     ON c.id = ch.company;

Notice that I added a COALESCE() so missing checks will not result in NULL values.

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

SQL: select distinct on column1 and sum up column2 values of merged rows

분류에서Dev

하위 쿼리의 SUM 가중치 일 때 SQL DISTINCT ID

분류에서Dev

postgresql의 SUM COUNT DISTINCT

분류에서Dev

input and sum the numbers - java

분류에서Dev

Linq to SQL order by with Distinct

분류에서Dev

sql to linq using distinct

분류에서Dev

SQL JOIN with DISTINCT

분류에서Dev

How to count the sum of distinct Excel values in a column?

분류에서Dev

Mysql - Sum only distinct row selected

분류에서Dev

oracle sql, id 's, group by one column, multiple distinct in other column

분류에서Dev

SQL select distinct entity - union all - order by another entity's column

분류에서Dev

mongodb $ sum only postive Numbers

분류에서Dev

Creating a Sum of numbers app with JavaScript

분류에서Dev

Find numbers with largest sum (Javascript)

분류에서Dev

SQL request with ORDER, DISTINCT and COUNT

분류에서Dev

SQL Server : COUNT (DISTINCT (CASE))

분류에서Dev

DISTINCT within count SQL Server

분류에서Dev

SQL Server : TOP과 Distinct

분류에서Dev

SQL Server 2008 R2에서 하나의 쿼리에서 distinct와 Sum을 실행하는 방법

분류에서Dev

distinct created_by and sum total_amount for each created_by

분류에서Dev

SQL SUM () 지원?

분류에서Dev

Aid with SQL SUM()?

분류에서Dev

SQL 개별 SUM

분류에서Dev

SQL COUNT And SUM

분류에서Dev

SQL Server SUM (값)

분류에서Dev

SQL, SUM + CASE

분류에서Dev

WorksheetFunction.Sum returning zero for numbers

분류에서Dev

Sum numbers return from a php function

분류에서Dev

Find m numbers that sum to n in a sequence