因此,我知道如何自行显示前5名和后5名。问题是如何将两者同时显示。这就是我所拥有的,但只显示底部的5。
SELECT SAL FROM ( SELECT DISTINCT SAL FROM EMP WHERE SAL IS NOT NULL ORDER BY SAL DESC ) WHERE ROWNUM <6 AND SELECT SAL FROM ( SELECT DISTINCT SAL FROM EMP WHERE SAL IS NOT NULL ORDER BY SAL ASC ) WHERE ROWNUM <6;
使用UNION或UNION ALL:
UNION
UNION ALL
SELECT SAL FROM ( SELECT DISTINCT SAL FROM EMP WHERE SAL IS NOT NULL ORDER BY SAL DESC ) WHERE ROWNUM < 6 UNION ALL SELECT SAL FROM ( SELECT DISTINCT SAL FROM EMP WHERE SAL IS NOT NULL ORDER BY SAL ASC ) WHERE ROWNUM < 6;
您还可以更简洁地将其编写为:
SELECT SAL FROM (SELECT DISTINCT SAL, DENSE_RANK() OVER (ORDER BY sal) as seqnum_asc, DENSE_RANK() OVER (ORDER BY sal) as seqnum_desc FROM EMP WHERE SAL IS NOT NULL ) s WHERE seqnum_asc < 6 OR seqnum_desc < 6;