How to sort a same column both in asc order and desc order

孤者浪人 提交于 2019-12-11 02:49:42

问题


With an SQL Query how do we get the output of 2 columns, the first one being a column sorted in asc order and the second one with the order desc and both are same columns.

ex:

emp table:
empid
1 
5
9
4

The query output should be

empid_1   empid_2
1          9
4          5
5          4
9          1

What OP tried so far

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; 

回答1:


If you use a common table expression/sub-query factoring clause then you only need to access the table once:

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



回答2:


You can do this with row_number() and self join:

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;

EDIT:

You could also do this with rownum but it requires an additional select:

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


来源:https://stackoverflow.com/questions/24304240/how-to-sort-a-same-column-both-in-asc-order-and-desc-order

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!