0

有人知道它会从输出中删除这样的重复项的语句吗?

DEPARTMENT_ID  DEPARTMENT_NAME                FULL_NAME               JOB_TITLE      
 50            Shipping                  Alana Walsh          Sales Representative
 50            Shipping                  Alana Walsh          Sales Representative  
 50            Shipping                  Winston Taylor       Sales Manager   
 50            Shipping                  Winston Taylor       Sales Manager
 60              IT                      Alexander Hunold     Sales Representative
 60              IT                      Alexander Hunold     Sales Representative

这是我到目前为止所拥有的:

select employees.department_id, departments.department_name, first_name || ' ' || last_name as full_name, job_title
from departments, employees, jobs
where employees.department_id = departments.department_id
and job_title like '%Sales%'
order by job_title, full_name;
4

3 回答 3

2

您可以使用SELECT DISTINCT删除重复项。

select distinct employees.department_id, departments.department_name, first_name || ' ' || last_name as full_name, job_title
from departments, employees, jobs
where employees.department_id = departments.department_id
and job_title like '%Sales%'
order by job_title, full_name;

或者,您也可以在每列上使用 GROUP BY

select employees.department_id, departments.department_name, first_name || ' ' || last_name as full_name, job_title
from departments, employees, jobs
where employees.department_id = departments.department_id
and job_title like '%Sales%'
group by employees.department_id, departments.department_name, first_name || ' ' || last_name as full_name, job_title
order by job_title, full_name;

看起来您还缺少工作机会?这可能是您的查询返回重复结果的原因。

我还建议您尽可能使用显式连接语法。

FROM departments
 INNER JOIN employees ON employees.department_id = departments.department_id
于 2013-03-07T22:05:36.027 回答
0

您可以DISTINCT按照 Matt Busche 的指示使用 a 。

然而,在许多情况下,人们错误地添加了 aDISTINCT以掩盖他们缺少连接条件的事实。在您的情况下,您将三个表连接在一起- departmentsemployeesjobs- 但您只有一个连接条件。因此,您正在对jobs表进行笛卡尔连接,这几乎肯定不是您想要的。该jobs表与其他两个表有何关系?如果我们假设job_id在 thejobsemployeestable 中都有 a,你会想要类似的东西

select employees.department_id, 
       departments.department_name, 
       first_name || ' ' || last_name as full_name, 
       job_title
  from departments, employees, jobs
 where employees.department_id = departments.department_id
   and jobs.job_id             = employees.job_id
   and job_title            like '%Sales%'
 order by job_title, full_name;
于 2013-03-07T22:12:09.930 回答
0

我想联合都可以产生这样的结果。基本上,您想根据我的理解复制数据集的每个不同行。

例如,如果查询是这样的: 查找 HR 部门的员工,输出结果一式两份。输出员工的名字和部门。

表名:工人列:worker_idint first_name varchar last_name varchar Salary int join_date datetime department varchar

select first_name , department from worker where department='HR' union all select first_name , department from worker where department='HR';

这将使每行两次,就像您在输出中一样。

因此,在您的情况下,您可以在临时表中获取不同的记录,然后在同一个表上进行自联接以根据需要塑造结果。这将是一项艰巨的任务,但我可以想到这个方向的解决方案。

于 2022-02-24T22:07:50.753 回答