Skip to content
Advertisement

How to merge two tables and sum the values with the same ID in SQL?

I am new to SQL sorry if the question ends up being trivial.

I have two tables:

Table 1 “Clients”:

Table 2 “Payments”:

Desired Output:

Here is what I have tried:

This sums the entries in table “payments” with the same ID.

However, I don’t know how to use the ID in order to have Name and Surname in front of total_payments (like in desired output).

Any help would be appreciated!

Advertisement

Answer

You can need JOIN to bring them into the query and then appropriate aggregation:

Note: Using a correlated subquery is often faster:

In particular, this can efficiently use an index on payments(customer_id, payment_amount).

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement