我有一组按"product_group_id"、"group_name"和"class"分组的数据.此组的产品名称不同.

CREATE TABLE rule (
   product_id integer
 , product_group_id integer
 , group_name text
 , class text
 , name text
);

INSERT INTO rule VALUES
  (1, 4, 'fruit', '0010', 'apple')
, (2, 4, 'fruit', '0010', 'cherry')
, (3, 4, 'fruit', '0010', 'pineapple')
, (4, 4, 'fruit', '0010', 'tomato')
, (5, 4, 'fruit', '0010', 'banana')
, (6, 4, 'fruit', '0010', 'peach')

在 Select 过程中,我想判断"名称"列表,如果"番茄"名称存在于集合中,我会将"无效"值或"有效"添加到新的"标签"列. 上述数据示例的结果将为(番茄名称存在):

product_group_id | group_name | class | label   |
------------------------------------------------
               4 |      fruit | 0010  | invalid |
             

或者,如果集合中不存在"番茄"名称,则该名称将有效:

product_group_id | group_name | class | label |
------------------------------------------------
               4 |      fruit | 0010  | valid |

到目前为止,如果番茄出现在集合中,我可以同时获得两个组的有效和无效.

select r.product_group_id, r.group_name, r.class, 
  case
    when r.name='tomato' then 'invalid'
    else 'valid'
  end label
from rule r
group by r.product_group_id, r.group_name, r.class, label;

product_group_id | group_name | class |   label |
------------------------------------------------
               4 |      fruit | 0010  |   valid |
               4 |      fruit | 0010  | invalid |

推荐答案

您需要使用聚合函数(例如max)来判断label上的tomatonot分组依据

select r.product_group_id, r.group_name, r.class, 
  case
    when max(case when r.name ='tomato' then r.name end) = 'tomato' then 'invalid'
    else 'valid'
  end label
from rule r
group by r.product_group_id, r.group_name, r.class

对于延长的样本日期(有两组)

INSERT INTO rule VALUES
  (1, 4, 'fruit', '0010', 'apple')
, (2, 4, 'fruit', '0010', 'cherry')
, (3, 4, 'fruit', '0010', 'pineapple')
, (4, 4, 'fruit', '0010', 'tomato')
, (5, 4, 'fruit', '0010', 'banana')
, (6, 4, 'fruit', '0010', 'peach')
, (7, 5, 'foo', '0020', 'bar');

结果如下所示

product_group_id|group_name|class|label  |
----------------+----------+-----+-------+
               5|foo       |0020 |valid  |
               4|fruit     |0010 |invalid|

Postgresql相关问答推荐

如何在PSQL中查询jsonb列包含字符串的嵌套数组

Org.postgresql.util.PSQLException:错误:函数LOWER(BYTEA)不存在

ST_Intersects 太慢

Docker compose read connection reset by peer error on pipeline

Postgresql如何从jsonB列的数组中的多个json中 Select 一个值

如何包装 record_out() 函数?

如何为 JavaEE 应用程序中的 PostgreSQL 热备设置配置连接故障转移?

postgres 和 python

运算符不存在:integer = integer[] 在使用 ANY 的查询中

从 sql 查询 postgres 9.4 创建嵌套 json

Postgresql - 在 Big Data 库中使用数组的性能

如何 Select 列值为空的行?

在远程机器上Restore dump

如何在 plpgsql 中使用记录类型变量?

NOT LIKE 带有 NULL 值的行为

由于外键约束无法删除对象

如何使 array_agg() 像 mySQL 中的 group_concat() 一样工作

psql 将默认 statement_timeout 设置为 postgres 中的用户

PostgreSQL 9.1:如何连接数组中的行而不重复,加入另一个表

错误:permission denied for language c