我刚开始学习SQL。我正在使用Oracle DB。
表emp与列empno,ename,job,mgr,hiredate,sal,comm,deptno。
我想从每个deptno的ename列获取第一条记录,并且ename必须按asc排序。
以下SQL有效:
Select ename
from (Select d.ename
From emp d
Where d.deptno = 10
Order by ename asc)
where rownum <= 1
Union
Select ename
from (Select d.ename
From emp d
Where d.deptno = 20
Order by ename asc)
where rownum <= 1
Union
Select ename
from (Select d.ename
From emp d
Where d.deptno = 30
Order by ename asc)
where rownum <= 1
Union
Select ename
from (Select d.ename
From emp d
Where d.deptno = 40
Order by ename asc)
where rownum <= 1
我想优化它,所以如果我将一些记录添加到deptno列,我就不需要重写它。
我试过SELECT
与
SELECT ename FROM emp WHERE (SELECT distinct deptno FROM emp)
答案 0 :(得分:0)
如果我理解您正在尝试正确执行的操作,则以下操作应该有效:
SELECT MIN(d.ename) as ename
FROM emp d
GROUP BY d.deptno
ORDER BY ename asc
答案 1 :(得分:0)
另一种方法
SELECT d.deptno,
(SELECT ename
FROM emp e
WHERE e.deptno = d.deptno AND ROWNUM <=1) ename
FROM dep d
<强> SQLFiddle 强>