0

This is the rather basic query I tried:

SELECT cust_id, prod_id, total_amount as total_revenue
FROM sales
GROUP BY prod_id;

Trying to make an output like this:

 cust_id | prod_id | total_revenue
---------+---------+--------------
 1       | 1       |        574.32
 1       | 2       |         78.09
 1       | 3       |          8.48
 2       | 1       |        706.11
 2       | 2       |        104.03
 2       | 3       |         58.01

But I get,

ERROR:  column "sales.cust_id" must appear in the GROUP BY clause or be used in an aggregate function

If I add all columns to GROUP BY, the output looks like this:

 cust_id | prod_id | total_revenue 
---------+---------+------------
 1       | 1       |        2.11
 1       | 1       |        0.80
 2       | 1       |        2.50
 1       | 1       |        3.13
 2       | 1       |        1.55
 1       | 1       |        0.75
 1       | 1       |        2.03

... (405 rows)

Here the top answer that says this is a 'common aggregation problem' but I haven't been able to implement it.

This solution talks about an optimizer.

Yet another fix uses "With cte" and gives a long solution but this seems like this should be a simple query. Thanks for reading.

2 Answers2

1

The problem you're having is due to the nature of the GROUP BY statement, when you use it you need to group all the fields that aren't part of the aggregate function (sum, max, min, etc) + one or more aggregate functions.

SELECT prod_id , cust_id, sum(total_amount) as total_revenue
FROM sales
GROUP BY prod_id, cust_id;
Douglas Figueroa
  • 675
  • 6
  • 17
  • 1
    Thanks, that gave the output I wanted when I added cust_id to the GROUP BY clause. Then I could drop the MAX() but it seemed to work both ways. – Steven Newton Jan 23 '21 at 07:18
0
SELECT prod_id , cust_id, sum(total_amount) as total_revenue
FROM sales
GROUP BY 1,2;
Jonathan
  • 41
  • 2
  • 5