【问题标题】:SQL query to check if a value isn't present用于检查值是否不存在的 SQL 查询
【发布时间】:2022-01-12 20:33:56
【问题描述】:

首先,我真的不知道如何表达我的问题。

我在数据库中有不同的公司。

我想知道哪些公司没有“分析师”简介。

这是我的查询:

select
t.name as "name"
t.pre as "first name"
t.id as "# account"
t.profile as "Profile"
b.cod_miss as "Mission"
b.df_missn as "End date"


from sr.v t 
inner join od.e_lds on t.niu_ld = b.niu_ld
where b.cod_miss = 'APPROV'
and t.profile = 'Analyst'

此查询为我提供了数据库中每个公司的所有分析师。 但我想拥有所有没有任何分析师的公司。 我该怎么做?我尝试使用 'and t.profile 'analyst'" 但显然效果不佳...

编辑

我尝试了接受的答案,但我注意到它只会返回给我所有不是分析师的人。

假设有一家有 3 名员工的公司 X。其中一位是分析师。我不希望那家公司出现在我的结果中。但如果 Y 公司有 2 名员工,而且他们都不是“分析师”,那么我希望这家公司出现在结果中。

【问题讨论】:

    标签: sql oracle


    【解决方案1】:

    如果我理解正确,那就是not exists。像这样的:

    select *
    from sr.v 
    where not exists (select null 
                      from od.e_lds b
                      where b.niu_ld = t.niu_ld
                        and t.profile = 'Analyst'
                     );
    

    应用于您的查询:

    select
      t.name as "name"
      t.pre as "first name"
      t.id as "# account"
      t.profile as "Profile"
      b.cod_miss as "Mission"
      b.df_missn as "End date"
    from sr.v t inner join od.e_lds b on t.niu_ld = b.niu_ld
    where b.cod_miss = 'APPROV'
      --
      and not exists (select null 
                      from od.e_lds c
                      where c.niu_ld = t.niu_ld
                        and t.profile = 'Analyst'
                     );
    

    [编辑 #2,带有一些示例数据]

    这是一个示例,显示了您试图用文字解释的内容(不过,如果您发布示例数据会更好)。如您所见,BMW 的一名员工是分析师,而 SAP 中没有人是 >> 因此,正在退回 SAP。

    SQL> with test (company, ename, profile) as
      2    (select 'BMW', 'Scott', 'Analyst' from dual union all
      3     select 'BMW', 'King' , 'Manager' from dual union all
      4     select 'BMW', 'Mike' , 'Clerk'   from dual union all
      5     --
      6     select 'SAP', 'John' , 'Clerk'   from dual union all
      7     select 'SAP', 'Fred' , 'Manager' from dual
      8    )
      9  select a.company, a.ename, a.profile
     10  from test a
     11  where not exists (select null
     12                    from test b
     13                    where b.company = a.company
     14                      and b.profile = 'Analyst');
    
    COMPANY    ENAME PROFILE
    ---------- ----- -------
    SAP        Fred  Manager
    SAP        John  Clerk
    
    SQL>
    

    【讨论】:

    • 谢谢你的回答,但你为什么删除了内连接?
    • 为简单起见。你知道如何使用它;你不知道如何做 NOT EXISTS 部分,这是这里的“关键”。
    • 我可以加入“where not exists”子句之前的表吗?
    • 很抱歉打扰您,但我不知道如何使它工作。我有需要满足的价值观,但我不知道把它们放在哪里。您能否编辑您的答案以完全符合我的原始查询与“不存在”子句?我迷路了,过去一个小时我一直在四处闲逛......
    • 我编辑了答案并添加了更多代码。如果它仍然不起作用,请 - 编辑您自己的问题并发布示例数据(说明问题的几行)和所需的输出;那我去看看。
    猜你喜欢
    • 1970-01-01
    • 2012-03-10
    • 1970-01-01
    • 2020-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-17
    相关资源
    最近更新 更多