Inner Join for 3 tables with SUM of two columns in SQL Query?

Mohamed Farook Mohamed Fazrin :

I have the following three tables:

Table Customer

Table Sales

Table Sales_Payment

I have Following Query to Join Above 3 Tables

     customer.customer_id,
     customer.name,
     SUM(sales.total),
     sales.created_at,
     SUM(sales_payments.amount)
FROM
     sales INNER JOIN customer ON customer.customer_id = sales.customer_id
     INNER JOIN sales_payments ON sales.customer_id = sales_payments.customer_id
WHERE sales.created_at ='2020-04-03'
GROUP By customer.name 

Result for Above Query is given below Query Output

Sum of sales.total is double of the actual sum of sales.total column which has 2-row count, I need to have the actual SUM of that column, without doubling the SUM of those rows, Thank you, for your help in advance..

Ashutosh Thakur :

PROBLEM

The problem here is that there are consecutive inner joins and the number of rows getting fetched in the second inner join is not restricted. So, as we have not added a condition on sales_payment_id in the join between the sales and sales_payment tables, one row in sales table(for customer_id 2, in this case) would be mapped to 2 rows in the payment table. This causes the same values to be reconsidered. In other words, the mapping for customer_id 2 between the 3 tables is 1:1:2 rather than 1:1:1.

SOLUTION

Solution 1 : As mentioned by Gordon, you could first aggregate the amount values of the sales_payments table and then aggregate the values in sales table.

Solution 2 : Alternatively (IMHO a better approach), you could add a foreign key between sales and sales_payment tables. For example, the sales_payment_id column of sales_payment table can be introduced in the sales table as well. This would facilitate the join between these tables and reduce additional overheads while querying data.

The query would then look like:

`SELECT c.customer_id,
  c.name,
  SUM(s.total),
  s.created_at,
  SUM(sp.amount)
FROM customer c
INNER JOIN sales s
ON c.customer_id = s.customer_id
INNER JOIN sales_payments sp
ON c.customer_id        = sp.customer_id
AND s.sales_payments_id = sp.sales_payments_id
WHERE s.created_at      ='2020-04-03'
GROUP BY c.customer_id,
c.name,
s.created_at ;`

Hope that helps!

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=407935&siteId=1