0

Here is create and insert script:

CREATE TABLE numbers (
  id integer NOT NULL,
  number1 integer NOT NULL
);

INSERT INTO numbers (id, number1) VALUES
  ('1', '1'),
  ('2', '1'),
  ('1', '2'),
  ('1', '3');

if the sum of number1 column is even return its average, other wise return 0. So it should return [id:1, number1:0] for above example

I have tried this:

select id,
  case
    when sum(number1) %2=1 then 0 else avg(number1)
  end as number1
from numbers

it works fine with mySql but not for PostgreSQL (I used http://sqlfiddle.com to try it out). error message in PostgreSQL is

 ERROR: column "numbers.id" must appear in the GROUP BY clause or be used in an aggregate function
1
  • 1
    Everytime you SELECT a column while using aggregate functions, this column must be in the GROUP BY list. This is what the error is telling you. Commented Jul 16, 2017 at 15:14

1 Answer 1

1

Why the expected value of id is 1 and not 2? Is this defined by the query in any way? MySql does not care about it, in contrary to Postgres (and other well known RDBMs).

If the value of id is negligible:

select
    case
        when sum(number1) %2 = 1 then 0 
        else avg(number1)
    end as number1
from numbers;

 number1 
---------
       0
(1 row) 

If you want to get e.g. the smallest value of id:

select
    min(id) as id,
    case
        when sum(number1) %2 = 1 then 0 
        else avg(number1)
    end as number1
from numbers;

 id | number1 
----+---------
  1 |       0
(1 row) 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer, the id was an unimportant row and as you said it caused the problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.