在同一个字段中选择升序和降序

时间:2013-07-18 07:45:57

标签: sql

___________________
| field1 | field1 |
|________|________|
|    A   |   E    |
|    B   |   D    |
|    C   |   C    |
|    D   |   B    |
|    E   |   A    |
|________|________|

如果可能的话,我会像上边的表一样选择相同的字段进行sql选择吗?

select t1.c, t2.c from
(
    WITH cte AS
    (
        SELECT 
            c,
            ROW_NUMBER() OVER(ORDER BY c DESC) AS n,
            ROW_NUMBER() OVER(ORDER BY c ASC) AS m
        FROM @t
    )
    SELECT t1.c, t2.c
    FROM cte t1
    JOIN cte t2 ON t2.n = t1.m
)
我可以做这样的事吗?

2 个答案:

答案 0 :(得分:7)

DECLARE @t TABLE ( c CHAR(1) )

INSERT INTO @t
VALUES ('a'),('b'),('c'),('d'),('e')

;WITH cte AS
(
    SELECT 
        c,
        ROW_NUMBER() OVER(ORDER BY c DESC) AS n,
        ROW_NUMBER() OVER(ORDER BY c ASC) AS m
    FROM @t
)

SELECT t1.c, t2.c
FROM cte t1
JOIN cte t2 ON t2.n = t1.m

编辑(评论):

如果您不想使用CTE,那么您可以将其写为

SELECT t1.c, t2.c 
FROM ( 
    SELECT c
        , ROW_NUMBER() OVER(ORDER BY c ASC) AS m 
    FROM @t 
) t1
JOIN ( 
    SELECT c
        , ROW_NUMBER() OVER(ORDER BY c DESC) AS n
    FROM @t 
) t2 ON t2.n = t1.m

SQLFiddle Demo

答案 1 :(得分:1)

使用temptables添加行号,您可以在下面的小提琴中看到

SQL Fiddle