这是您的原始查询:
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;