下面的代码是重复我的部门名称结果,我不知道为什么。我需要显示部门的名称,在那里工作的员工的工作ID和工资。另外,我需要弄清楚是否在CUBE表达式中使用了department_id或job_id。
SELECT d.department_name AS "Name",
e.job_id AS "Job ID",
SUM(e.salary) AS "salary",
DECODE(GROUPING(d.department_id),1, 'Yes', 'No') AS "Department Used",
DECODE(GROUPING(e.job_id), 1, 'Yes', 'No') AS "Job used"
FROM employees e
full OUTER JOIN departments d
ON (e.department_id = d.department_id)
GROUP BY CUBE(d.department_name, e.job_id, d.department_id)
ORDER BY d.department_name;
答案 0 :(得分:0)
因为cube会为所有组合生成小计。在您的示例中,组合的工作方式如下:
1)department_name - job_id - department_id
2)department_name - job_id
3)department_name - department_id
4)department_name
5)job_id - department_id
6)job_id
7)department_id
8)(总计)
这就是你获得重复值的原因。
我不知道你到底需要什么,但我认为你需要这样的东西:
select d.department_name as "Name",
e.job_id as "Job ID",
sum(e.salary) as "Salary",
decode(grouping(d.department_id), 1, 'Yes', 'No') as "Department Used",
decode(grouping(e.job_id), 1, 'Yes', 'No') as "Job Used"
from hr.employees e
full outer join hr.departments d
on (e.department_id = d.department_id)
group by cube(e.job_id), d.department_name, d.department_id
order by d.department_name;
答案 1 :(得分:0)
问题在于您的CUBE()
子句:您在DEPARTMENT中包含两个属性,因此对于DEPARTMENT_ID和DEPARTMENT_NAME的所有组合,结果都是立方体。
然而,这两列是相关的:ID和NAME之间存在一对一的关系(假设您正在使用HR模式或其他一些不错的数据模型)。
因此解决方案非常简单:将CUBE()
子句更改为使用一个。由于DEPARTMENT_NAME正在进行预测,因此需要选择。您需要更改DECODE()
以匹配。
SELECT d.department_name AS "Name",
e.job_id AS "Job ID",
SUM(e.salary) AS "salary",
DECODE(GROUPING(d.department_name),1, 'Yes', 'No') AS "Department Used",
DECODE(GROUPING(e.job_id), 1, 'Yes', 'No') AS "Job used"
FROM employees e
full OUTER JOIN departments d
ON (e.department_id = d.department_id)
GROUP BY CUBE(d.department_name, e.job_id)
ORDER BY d.department_name;