简体   繁体   English

PostgreSQL 9.6使用基于列总和的case-when子句

[英]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.

相关问题 在Teradata中使用大小写 - Using Case-When in Teradata 函数POSTGRESQL中的CASE-WHEN - CASE-WHEN within function POSTGRESQL Postgresql 在 ORDER BY 子句中使用 CASE 表达式时,“列必须出现在 GROUP BY 子句中或用于聚合函数” - Postgresql "Column must appear in the GROUP BY clause or be used in an aggregate function" when using CASE expression inside ORDER BY clause 实体框架强制CASE-WHEN列不可为空 - Entity Framework Force CASE-WHEN column to be not nullable 如何在SQL中使用Case-When设置优先级 - How can I set priority using Case-When in SQL 在存储过程中使用case-when语句语法 - Using case-when statement in stored procedure Syntax 通过表达式很好地选择和分组,而无需使用大小写 - Nicely selecting and grouping by expressions, without using case-when 使用Case-When在SQL中将多行转换为单行 - Convert multiple rows in to single row in SQL using Case-When 在多种条件下使用 case-when 进行复杂查询 - Using case-when for complex query under several condition 使用case语句时,PostgreSQL列必须出现在GROUP BY子句中或在聚合函数中使用 - PostgreSQL column must appear in the GROUP BY clause or be used in an aggregate function when using case statement
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM