'Sum not working when using with, sum, group by, order by and from
I have code that gets columns from two different tables in order to show customer IDs and sum all the products they used for the duration of their subscription. However the code is not summing so for a table like this, I want the output to be the same columns except product usage is summed by product and master_id.
master_id | product | product_usage | id | billing_period_start_date | start_date |
---|---|---|---|---|---|
1 | apples | 2 | 1 | January 1 | January 1 |
1 | apples | 5 | 1 | February 1 | January 1 |
1 | oranges | 3 | 1 | January 1 | January 1 |
2 | oranges | 1 | 2 | January 1 | January 1 |
2 | oranges | 7 | 2 | February 1 | January 1 |
2 | apples | 2 | 2 | January 1 | January 1 |
Output
master_id | product | product_usage | id | billing_period_start_date | start_date |
---|---|---|---|---|---|
1 | apples | 7 | 1 | January 1 | January 1 |
1 | oranges | 3 | 1 | January 1 | January 1 |
2 | oranges | 8 | 2 | January 1 | January 1 |
2 | apples | 2 | 2 | January 1 | January 1 |
but my code is not doing the sum and is returning everything separately like the first table. Any ideas on how to fix?
with results as
(select bill.master_id,
bill.product,
sum(bill.product_usage),
subscription.id,
bill.billing_period_start_date,
subscription.start_date,
from
bill,
subscription
where bill.master_id = subscription.id
and master_id in ('1',
'2',
'3',
'4',
'5',)
and billing_period_start_date >= start_date
group by master_id, product, id, billing_period_start_date, start_date
order by master_id
)
select * from results
Solution 1:[1]
Maybe like this?
select
bi.master_id,
bi.product,
su.id,
bi.billing_period_start_date,
su.start_date,
sum(bi.product_usage)
from
bill bi,
subscription su
where
bi.master_id = su.id and bi.master_id in ('1','2','3','4','5') and bi.billing_period_start_date >= su.start_date
group by
bi.master_id,
bi.product,
su.id,
bi.billing_period_start_date,
su.start_date
order by bi.master_id;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |