SELECT Table 1 中的 DISTINCT 用户在 Table 2 中不存在

SELECT DISTINCT Users in Table 1 which don't exist in Table 2

我有一个包含 4 列用户信息的 table。每个 table 都有以下列:

Username | Full_Name | Job_Name | Current_Job_Allowed

Table 1 包括所有用户和他们有权查看的 Job_Name。这意味着 Table 1 中有多行具有不同 Job_Name 值的相同用户名。

Table 2 包含所有可能用户的列表。

Username      |Full_Name
--------------+-----------------
amunoz        |Andrew Munoz
csmith        |Carl Smith
cwatkins      |Cat Watkins
ggriffiths    |Garmin Griffiths
jcarr         |Jason Carr
jhothi        |Jark Hothi
jphillips     |Jim Phillips
lbradfield    |Lisa Bradfield
ntaylor       |Noria Taylor
rfelipe       |Ralf Felipe

查询 1 包含由我指定的查询参数指定的所有用户,即 'KML_20160531'。

我现在想要 select 一个 DISTINCT 列表,其中包含与我为 Job_Name 指定的参数具有不同 Job_Name 的所有用户。例如 Table 1 包含:

Username|Full_Name   |Job_Name    |Current_Job_Allowed
--------+------------+------------+----------------------
amunoz  |Andrew Munoz|KML_20160531|1
jcarr   |Jason Carr  |KML_20160531|1
rfelipe |Ralf Felipe |KML_20140531|1
amunoz  |Andrew Munoz|KML_20160431|1

当我为 Job_Name 输入 20160531 时,我想 return 下面的内容。对于我输入的 Job_Name 值,这将 return 所有可能的新用户。

Username      |Full_Name
--------------+---------------
csmith        |Carl Smith
cwatkins      |Cat Watkins
ggriffiths    |Garmin Griffiths
jhothi        |Jark Hothi
jphillips     |Jim Phillips
lbradfield    |Lisa Bradfield
ntaylor       |Noria Taylor
rfelipe       |Ralf Felipe

您可以使用 not in 和 distinct

select distinct a.username, a.fullname 
from table1 as a 
where a.username not in (select distinct username  
                  from table2 where job_name ='my_value');

并且仅针对工作

select distinct a.username, a.fullname 
from table1 as a 
where a.username not in (select  username  
                   from table2 
                   group by username 
                   having count(job_name) = 1 
                   and job_name ='my_value'   );

这将是您的问题的语法

SELECT DISTINCT UserName 
FROM Table1 
WHERE UserName NOT IN (
    SELECT UserName From Table2 
    WHERE job_name = ''
);

您实际上根本不需要 DISTINCT 此查询:

select t.*
from table1 as t
where not exists (select 1
                  from table2 as t2
                  where t2.username = t.username and t2.job_name = "KML_20160531"
                 );

根据您对问题的描述,Current_Job_Allowed 似乎不相关。

此参数查询将显示哪些用户有 Table 1Job_Name 匹配参数值:

PARAMETERS which_job Text ( 255 );
SELECT t1.[Username], t1.Job_Name
FROM [Table 1] AS t1
WHERE t1.Job_Name=[which_job];

因此您可以将其用作子查询,左连接 Table 2 到子查询,select "right side" 为 Null 的行:

PARAMETERS which_job Text ( 255 );
SELECT t2.[Username]
FROM
    [Table 2] AS t2
    LEFT JOIN
        (
            SELECT t1.[Username]
            FROM [Table 1] AS t1
            WHERE t1.Job_Name=[which_job]
        ) AS sub
    ON t2.[Username] = sub.[Username]
WHERE sub.[Username] Is Null;

假设查询 returns 正确的行,将您要查看的其他字段添加到 SELECT t2.[Username]

你不需要 DISTINCT 除非 Table 2 允许重复的 Username 值,或者 Table 1 允许多行具有相同的 Username 组合和 Job_Name.