当我学习SQL语句时,我遇到了一个例子(关于demo SCOTT数据库),我不知道如何解决。
哪些部门都在场?
我最有希望的方法是将所有salgrades和部门分组到联接表 emp , dept 和 salgrade :
SELECT s.grade AS "Salgrade",
d.dname AS "Department ID"
FROM emp e INNER JOIN dept d ON(e.deptno = d.deptno)
INNER JOIN salgrade s ON(e.sal BETWEEN s.losal AND s.hisal)
GROUP BY d.dname, s.grade
执行此操作会给我以下结果:
如果我可以按部门再次分组, COUNT(*)可以给我每个部门不同的salgrades数量。然后我可以将这个数字(用 HAVING )与以下子选项进行比较:
(SELECT COUNT(*)
FROM salgrade)
是否有可能对已经包含的表进行分组 GROUP BY ? 我可以使用另一种(更好的)方法吗?
我正在使用带有“Application Express 4.2.4.00.07”的apex-oracle-server
答案 0 :(得分:1)
通过删除内部分组,对您的版本进行微小更改,此版本首先生成所有员工的salgrade
和department
,然后在外部进行分组,计算不同的工资等级。< / p>
SELECT Department_ID
FROM
(
SELECT s.grade AS Salgrade,
d.dname AS Department_ID
FROM emp e
INNER JOIN dept d ON(e.deptno = d.deptno)
INNER JOIN salgrade s ON(e.sal BETWEEN s.losal AND s.hisal)
)
GROUP BY Department_ID
HAVING COUNT(distinct Salgrade) = ( SELECT count(1) FROM salgrade);
答案 1 :(得分:1)
我现在找到了一个更简单的解决方案:
SELECT d.dname
FROM emp e INNER JOIN dept d ON(e.deptno = d.deptno)
INNER JOIN salgrade s ON(e.sal BETWEEN s.losal AND s.hisal)
GROUP BY d.dname
HAVING COUNT(DISTINCT s.grade) = (SELECT COUNT(*) FROM salgrade);
答案 2 :(得分:0)
简单的方法是 - 如果性能不是问题。
SELECT
COUNT(DISTINCT [Salgrade]) AS [COUNT]
,[Department ID]
FROM (SELECT s.grade AS "Salgrade",
d.dname AS "Department ID"
FROM emp e INNER JOIN dept d ON(e.deptno = d.deptno)
INNER JOIN salgrade s ON(e.sal BETWEEN s.losal AND s.hisal)
GROUP BY d.dname, s.grade) DEPT_SALE
GROUP BY [Department ID]
如果我们了解更多基本表格,emp
&amp; salegrade