[英]How to select the same column twice with different order
Here is my problem. 这是我的问题。 I need to order the same colum in diferent ways in the same select. 我需要在同一个选择中以不同的方式订购相同的列。 First asc and then desc. 首先是asc,然后是desc。
Example: 例:
Table1 表格1
+--------+-----+
| Name | Age |
+--------+-----+
| Coa | 20 |
| Bami | 12 |
| Alice | 50 |
+--------+-----+
The results should be: 结果应该是:
+------+-----+
| Age | Age |
+------+-----+
| 12 | 50 |
| 20 | 20 |
| 50 | 12 |
+------+-----+
I want the same column first orders Ascendant and then Descendant. 我希望同一列首先订购Ascendant,然后是Descendant。
I am trying 我在尝试
Query 询问
Select t1.age, t2.age
from table1 t1
inner join table1 t2
on t1.name=t2.name
order by t1.age asc, t2.age desc
But in the result, both columns ordered in the same way. 但在结果中,两列都以相同的方式排序。
Anyone knows how to solve this problem? 谁知道如何解决这个问题?
That is a really weird requirement. 这是一个非常奇怪的要求。 You can do this using row_number()
and a join: 您可以使用row_number()
和连接执行此操作:
select t1a.age, t1b.age
from (select t1.*, row_number() over (order by age asc) as seqnum
from table1 t1
) t1a join
(select t1.*, row_number() over (order by age desc) as seqnum
from t1
) t1b
on t1a.seqnum = t1b.seqnum
order by t1a.age;
WITH CTE AS
(
SELECT NAME,
AGE,
ROW_NUMBER() OVER(ORDER BY AGE ASC) AS AC,
ROW_NUMBER() OVER(ORDER BY AGE DESC) AS DC
FROM YOURTABLE
)
SELECT C1.AGE,C2.AGE
FROM CTE C1
INNER JOIN CTE C2 ON C1.AC=C2.DC
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.