使用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 :(得分: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
:
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;
答案 1 :(得分: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