I have this table:
product | amount | no_of_customers |
---|---|---|
Prdct_1 | 100 | 9 |
Prdct_1 | 200 | 15 |
Prdct_2 | 50 | 2 |
Prdct_3 | 40 | 5 |
Prdct_3 | 80 | 5 |
Prdct_4 | 10 | 1 |
I want to join this with the below table
product | no_of_bills |
---|---|
Prdct_1 | 6 |
Prdct_1 | 3 |
Prdct_2 | 4 |
Prdct_3 | 10 |
Prdct_3 | 5 |
Prdct_4 | 2 |
Additionally, I want to add a sum of all categories. So the result should look like this:
product | amount | no_of_customers | no_of_bills |
---|---|---|---|
Prdct_1 | 300 | 24 | 9 |
Prdct_2 | 50 | 2 | 4 |
Prdct_3 | 120 | 10 | 15 |
Prdct_4 | 10 | 1 | 2 |
Total | 480 | 35 | 30 |
How could I solve it? Thanks for your answers.
3
Answers
I do not have postgres to test immediately, but look at this
sql
, Hope this works for you…The
sql
creates a temporary tablet
from the two tables usingUNION ALL
operation which allows merging tables irrespective of duplicated rows exists or not.The query then groups the data in the table
t
by the product column wherein all rows with the same product name are grouped together.For each group, the query sums up the values in columns
amount
,no_of_customers
, andno_of_bills columns
, and returns the results in the following order:product
,amount
,no_of_customers
,no_of_bills
.That’s the logic
I’m not sure if this is the simplest possible solution, but it works for me. I named your tables
products
andbills
:I’m using the Common Table Expression (CTE)
product_summary
to calculate the sum ofamount
andno_of_customers
for each product in theproducts
table. The CTEbill_summary
calculates the sum ofno_of_bills
for each product in thebills
table. These two results are then combined withUNION ALL
.You can use
group by
withgrouping sets
to calculate subtotals and a total, then use join to combine both results fromCTE
s:Result :
Demo here