我有以下查询,显示特定组(A1,B1..etc)和特定部门的员工总数。
问题是在特定日期没有特定部门的数据,然后根本没有显示具有部门名称的行,我希望查询显示所有行/部门名称,即使他们有数据是不是。在这种情况下应该显示“0”。
SELECT NVL(TO_CHAR(COALESCE(dept_name,'NA') ),'TOTAL') AS Department,
SUM (
CASE
WHEN ( emp_group IN('ABC','CDE','EFG','GHI'))
THEN 1
ELSE 0
END) AS A1,
SUM(
CASE
WHEN ( emp_group IN ('XYZ'))
THEN 1
ELSE 0
END) AS B1,
SUM (
CASE
WHEN ( emp_group IN ('ABC','CDE','EFG','GHI','XYZ'))
THEN 1
ELSE 0
END) AS TOTAL
FROM emp e
WHERE
dept_name IN('IT','FI','ACC')
AND e.transaction_date = trunc(sysdate)
GROUP BY rollup(COALESCE(dept_name,'NA'))
提前致谢
答案 0 :(得分:1)
从departments
开始(您应该有类似的东西......)并进行左连接:
SELECT NVL(TO_CHAR(COALESCE(d.dept_name,'NA') ),'TOTAL') AS Department,
SUM (
CASE
WHEN ( emp_group IN('ABC','CDE','EFG','GHI'))
THEN 1
ELSE 0
END) AS A1,
SUM(
CASE
WHEN ( emp_group IN ('XYZ'))
THEN 1
ELSE 0
END) AS B1,
SUM (
CASE
WHEN ( emp_group IN ('ABC','CDE','EFG','GHI','XYZ'))
THEN 1
ELSE 0
END) AS TOTAL
FROM departments d
left join emp e on d.dept_id = e.dept_id
WHERE
d.dept_name IN('IT','FI','ACC')
AND e.transaction_date = trunc(sysdate)
GROUP BY rollup(COALESCE(d.dept_name,'NA'));
如果您没有部门,可以通过以下方式离开加入对象:
SELECT NVL(TO_CHAR(COALESCE(e.dept_name,'NA') ),'TOTAL') AS Department,
SUM (
CASE
WHEN ( emp_group IN('ABC','CDE','EFG','GHI'))
THEN 1
ELSE 0
END) AS A1,
SUM(
CASE
WHEN ( emp_group IN ('XYZ'))
THEN 1
ELSE 0
END) AS B1,
SUM (
CASE
WHEN ( emp_group IN ('ABC','CDE','EFG','GHI','XYZ'))
THEN 1
ELSE 0
END) AS TOTAL
FROM (select 'IT' as dept_name from dual union all
select 'FI' from dual union all
select 'ACC' from dual) d
left join emp e on d.dept_name = e.dept_name
WHERE
e.transaction_date = trunc(sysdate)
GROUP BY rollup(COALESCE(e.dept_name,'NA'));