[英]PostgreSQL 9.6 using case-when clause based on sum of the column
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 如果number1列的总和甚至返回其平均值,否则返回0。因此对于上面的示例,它应返回[id:1,number1:0]
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). 它可以与mySql一起正常工作,但不适用于PostgreSQL(我使用http://sqlfiddle.com进行了尝试)。 error message in PostgreSQL is PostgreSQL中的错误消息是
ERROR: column "numbers.id" must appear in the GROUP BY clause or be used in an aggregate function
Why the expected value of id
is 1
and not 2
? 为什么id
的期望值为1
而不是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). 与Postgres(和其他众所周知的RDBM)相反,MySql并不关心它。
If the value of id
is negligible: 如果id
的值可以忽略不计:
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 eg the smallest value of id
: 如果要获取例如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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.