postgresql—确定作业是否为“仅限内部”的sql

xqkwcwgp  于 2021-07-24  发布在  Java
关注(0)|答案(4)|浏览(271)

我正在处理招聘数据,并希望产生的输出,将让我知道,如果一个工作是'内部唯一'(这意味着它只是张贴到一个内部工作委员会,而不是任何外部工作委员会)。我所期望的输出是每个作业一行,其中只有一列显示true或false。
我有一个表,它提供了带有作业id和作业板名称的行,以及一个表示作业是否发布到该站点的“live”列。
我在以下位置创建了一个数据集:https://rextester.com/fhu87800

CREATE TABLE job_posts(
    ID INT NOT NULL
    , job_id INTEGER NOT NULL
    , job_board_name VARCHAR(50) NOT NULL
    , live BOOLEAN);

INSERT INTO job_posts(id,job_id,job_board_name,live) VALUES (1,20035,'internal',TRUE);
INSERT INTO job_posts(id,job_id,job_board_name,live) VALUES (2,20035,'company_external_1',TRUE);
INSERT INTO job_posts(id,job_id,job_board_name,live) VALUES (3,20035,'company_external_2',TRUE);
INSERT INTO job_posts(id,job_id,job_board_name,live) VALUES (4,20036,'internal',TRUE);
INSERT INTO job_posts(id,job_id,job_board_name,live) VALUES (5,20036,'company_external_1',FALSE);
INSERT INTO job_posts(id,job_id,job_board_name,live) VALUES (6,20036,'company_external_2',FALSE);
INSERT INTO job_posts(id,job_id,job_board_name,live) VALUES (7,20036,'company_external_3',FALSE);
INSERT INTO job_posts(id,job_id,job_board_name,live) VALUES (8,20037,'internal',TRUE);
INSERT INTO job_posts(id,job_id,job_board_name,live) VALUES (9,20037,'company_external_1',FALSE);
INSERT INTO job_posts(id,job_id,job_board_name,live) VALUES (5,20036,'company_external_2',TRUE);

SELECT *
FROM job_posts
ORDER BY 1

我想要的输出将显示job\u id 20037为internal\u only=true,其他job为false。
提前感谢您的帮助!

7gyucuyw

7gyucuyw1#

使用 filter 带的子句 bool_or() 要实现这一点:

with summarize as (
 select job_id, 
       bool_or(live) filter (where job_board_name = 'internal') as internal, 
       bool_or(live) filter (where job_board_name like 'company_external%') as external 
  from job_posts 
 group by job_id
)
select job_id 
  from summarize 
 where internal and not external;

 job_id 
--------
  20037
5us2dqdw

5us2dqdw2#

可以使用反连接来查找所需的行。例如:

select a.job_id
from (
  select distinct job_id 
  from job_posts 
  where job_board_name = 'internal' and live
) a
left join (
  select distinct job_id 
  from job_posts 
  where job_board_name like 'company_external_%' and live
) b on a.job_id = b.job_id
where b.job_id is null

结果:

job_id
------
20037

参见db fiddle的运行示例。

h9vpoimq

h9vpoimq3#

您可以选择活动的内部作业,然后使用“不存在”来消除也具有外部过帐的内部过帐。

select j.job_id
  from job_posts j
 where j.job_board_name = 'internal'
   and j.live 
   and not exists 
       (select null
          from job_posts j2
         where j2.job_id = j.job_id
           and j2.job_board_name != 'internal'
           and j2.live
        );
46qrfjad

46qrfjad4#

你必须写一个案例查询。

select id,job_id,job_board_name,live, case when job_board_name='internal' then 'TRUE' else 'False' end as internal_only from job_posts

相关问题