0

执行查询时出现错误。我不知道似乎是什么问题。我正在尝试查询数据库以找出两个或多个部门的员工。(即 Staff_ID = 1,在 DEPT_ID = 4 和 6 下工作)。涉及三个表:

1. STAFF
2. DEPARTMENT
3. STAFF_DEPT (contains ID of STAFF and DEPT)

这是我所做的,

SELECT
sd.STAFF_ID || ' ' || s.STAFF_NAME AS "Staff Name",
d.DEPT_NAME AS "Department"
FROM STAFF_DEPT sd
INNER JOIN STAFF s ON sd.STAFF_ID = s.STAFF_ID 
INNER JOIN DEPARTMENT d ON sd.DEPT_ID = d.DEPT_ID
GROUP BY sd.STAFF_ID
HAVING COUNT (sd.STAFF_ID) > 1
4

3 回答 3

2

这是您的原始查询:

SELECT sd.STAFF_ID || ' ' || s.STAFF_NAME AS "Staff Name",
       d.DEPT_NAME AS "Department"
FROM STAFF_DEPT sd
INNER JOIN STAFF s ON sd.STAFF_ID = s.STAFF_ID 
INNER JOIN DEPARTMENT d ON sd.DEPT_ID = d.DEPT_ID
GROUP BY sd.STAFF_ID
HAVING COUNT (sd.STAFF_ID) > 1;

您的查询的问题是您正在对 进行聚合staff_id,但是您有列staff_name并且dept_name在您的聚合中。您正在寻找多个部门的员工。您可以使用以下方式获得每人一行的部门列表:

SELECT sd.STAFF_ID || ' ' || s.STAFF_NAME AS "Staff Name",
       list_agg(d.DEPT_NAME, ',') within group (order by DEPT_NAME) AS "Department_List"
FROM STAFF_DEPT sd
INNER JOIN STAFF s ON sd.STAFF_ID = s.STAFF_ID 
INNER JOIN DEPARTMENT d ON sd.DEPT_ID = d.DEPT_ID
GROUP BY sd.STAFF_ID, s.STAFF_Name
HAVING COUNT (sd.STAFF_ID) > 1;

注意:我list_agg()在.selects.staff_namegroup by

如果您希望每行一个人/一个部门,请使用具有分析功能的子查询:

selectsd.STAFF_ID || ' ' || s.STAFF_NAME AS "Staff Name", dept_name
from (select sd.staff_id, s.staff_name, d.dept_name,
             count(*) over (partition by sd.staff_id, s.staff_name) as NumDepts
      FROM STAFF_DEPT sd
      INNER JOIN STAFF s ON sd.STAFF_ID = s.STAFF_ID 
      INNER JOIN DEPARTMENT d ON sd.DEPT_ID = d.DEPT_ID
     ) t
where NumDepts > 1;
于 2013-05-18T14:02:13.503 回答
1

试试这个:

with temp as
(select sd.staff_id from staff_dept sd
group by staff_id
having count(staff_id)>1)
select tp.staff_id||' ' ||s.Name AS "Staff Name", d.DNAME
FROM temp tp, 
staff_dept sd,
staff s,
dept d
where tp.staff_id=sd.staff_id
and sd.staff_id=s.id
and sd.dept_id=d.deptno;

我已将计数超过 1 的 staff_id 存储在临时视图中,并在最终选择查询中使用它。

正如我之前向 techdo 提到的,您不能按 sd.STAFF_ID || 分组 ' ' || s.STAFF_NAME, d.DEPT_NAME 因为它始终是唯一的,并且始终计为 1。

于 2013-05-18T05:41:37.780 回答
0

请试试:

SELECT
  sd.STAFF_ID || ' ' || s.STAFF_NAME AS "Staff Name",
  d.DEPT_NAME AS "Department"
FROM STAFF_DEPT sd
  INNER JOIN STAFF s ON sd.STAFF_ID = s.STAFF_ID 
  INNER JOIN DEPARTMENT d ON sd.DEPT_ID = d.DEPT_ID
GROUP BY sd.STAFF_ID || ' ' || s.STAFF_NAME, d.DEPT_NAME
HAVING COUNT (sd.STAFF_ID) > 1
于 2013-05-18T04:31:13.227 回答