2014-06-19 268 views
2

使用SQL查詢如何獲得2列的輸出,第一列是按asc順序排序的列,第二列是排序順序desc和是同一列。如何按順序排序和排序順序排列相同的列

例如:

emp table: 
empid 
1 
5 
9 
4 

查詢輸出應該

empid_1 empid_2 
1   9 
4   5 
5   4 
9   1 

什麼OP試過到目前爲止

WITH emp1 
    AS (SELECT ROWNUM a, 
       empno 
     FROM (SELECT empno 
       FROM emp 
       ORDER BY 1 ASC)), 
    emp2 
    AS (SELECT ROWNUM b, 
       empno 
     FROM (SELECT empno 
       FROM emp 
       ORDER BY 1 DESC)) 
SELECT emp1.empno, 
     emp2.empno 
FROM emp1, 
     emp2 
WHERE emp1.a = emp2.b; 
+0

@visakh:下面是我試圖 與EMP1如( 選擇ROWNUM一個,從(通過EMPNO 1個ASC從EMP順序選擇EMPNO) ), emp2 as( select rownum b,empno from(select empno from emp order by 1 desc) )select emp1.empno,emp2.​​empno from emp1, – Avinash

+0

請修改問題而不是評論。 –

回答

1

如果您使用公用表表達式/子查詢保條款,那麼你只需要一次訪問表:

with the_data as (
select empid 
     , row_number() over (order by empid) as id_asc 
     , row_number() over (order by empid desc) as id_desc 
    from emp 
     ) 
select a.empid as empid_asc 
    , d.empid as empid_desc 
    from the_data a 
    join the_data d 
    on a.id_asc = d.id_desc 
5

您可以row_number()和自我做這個連接:

select e1.empid as empid_1, e2.empid as empid_2 
from (select e.*, row_number() over (order by emp_id) as seqnum 
     from emp e 
    ) e1 join 
    (select e.*, row_number() over (order by emp_id desc) as seqnum 
     from emp e 
    ) e2 
    on e1.seqnum = e2.seqnum; 

編輯:

你也可以用rownum做到這一點:

select e1.empid as empid_1, e2.empid as empid_2 
from (select e.*, rownum as seqnum 
     from emp e 
     order by empid asc 
    ) e1 join 
    (select e.*, rownum as seqnum 
     from emp e 
     order by empid desc 
    ) e2 
    on e1.seqnum = e2.seqnum; 
+0

+1非常快,只是想到'rownum' :) – MinhD

+1

'rownum'版本不能像寫入一樣工作 - 你需要嵌套選擇,以便'rownum'在'order by'之後應用 - 目前它在之前。 –