Skip to content
Advertisement

SQL – sum a column with common id, then coalesce total with another column

I know somebody can tell me what I’m doing incorrectly here. This is a postgresql db. I’m trying to first sum the values in a column that share the same ID, and then add that total (coalesce) with another column.

First, this is how I total up the values within a column that share a common order.id:

This is how I add the values of 2 columns together:

So how might I go about combining the two, and first finding the sum of all values that share a common order.id, and then adding that sum to the other column (order_item.iva_on_purchase_price).

Would this be incorrect?

What’s the right way to do something like this?

Advertisement

Answer

You can create two CTE one for first sum and other for second data you want and then you can join the two CTE see below example code

if you generate sql fiddle with sample table we can try result

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