执行查询时出错。我不知道这似乎是什么问题。我正在尝试查询数据库,以找出两个或更多部门的员工。 (即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
答案 0 :(得分: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()
和select
s.staff_name
中添加了group 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;
答案 1 :(得分: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;
我在临时视图中存储了employee_id的计数超过1,并在最终的选择查询中使用它。
正如我之前向techdo提到的那样,你不能通过sd.STAFF_ID ||进行分组''|| s.STAFF_NAME,d.DEPT_NAME,因为它始终是唯一的,并且总是算作1。
答案 2 :(得分: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