我有以下 Select :

SELECT
    posm.id AS org_scope_metric_id,
    cc.code AS control_code,
    ccp.code AS part_code,
    pop.id AS program_id
FROM public.org_scope_metric posm
JOIN public.org_metric pom ON pom.id = posm.metric_id
JOIN compliance.metric cm ON cm.id = pom.metric_id
JOIN compliance.control_part_metric ccpm ON ccpm.metric_id = cm.id
JOIN compliance.control_part ccp ON ccp.id = ccpm.part_id
JOIN compliance.control cc ON cc.id = ccp.control_id
JOIN compliance.program_framework cpf ON cpf.framework_id = cc.framework_id
JOIN public.org_program pop ON pop.program_id = cpf.program_id
WHERE posm.scope_id ='e6d11bfe-e5fc-11ee-8cda-238cdb93d281'
GROUP BY posm.id, cc.code, ccp.code, pop.id

that returns such result: enter image description here

如果有org_scope_metric_id个不同的program_id,我需要从 Select 中跳过它们.

请帮助解决!

推荐答案

统计每组中相等的org_scope_metric_id次出现的次数和不同的program_id-S的次数,然后过滤结果行中大于1的both个数字.

with t as ( 
  select *, 
    count(*) over w cnt,
    array_agg(program_id) over w program_id_list
  from (<your query here>) t 
  window w as (partition by org_scope_metric_id)
)
select * from t 
where cnt > 1 and array_distinct_count(program_id_list) > 1;

你需要一个辅助函数来实现—

create or replace function array_distinct_count(arr anyarray)
returns integer language sql immutable as $$
 select count(distinct el) from unnest(arr) el;
$$;

Sql相关问答推荐

用相同值更新行

从列的不同值创建列

使用SQL旋转表的列(Snowflake)

删除MariaDB数据库中的JSON数据

我希望以正确的升序获取SQL结果.怎样才能得到它们?

当一个视图在Postgres中失效时?

在Oracle SQL中将列值转换为行

两个不同星期的销售额,不加成一行

仅当交叉应用返回单值时才更新记录

Redshift PL/pgSQL循环中的参数化列名

更正用于判断错误组合的SQL

显示所有组并计算给定组中的项目(包括 0 个结果)

如何将 START 和 END 日期之间的日期差异作为 SQL 中的单独列获取

SQL ORACLE - 查找连续天数

检索具有相同位置的最小和最大store 数量

如何根据与 BigQuery 中另一个表的匹配更新一个表中的列?

SQL Server 查找存在于所有不同时期(或序列)中的条目

在 Microsoft SQL Server 中,如何只为特定值保留不同的行?

SQL Server Where 条件

使用 JSON_BUILD_OBJ 从 Postgres 返回 JSON