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

If possible I do the sql selection like upside table with same field same table?

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
)

can i do something like this?

4

2 回答 2

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

编辑(评论):

如果你不想使用 aCTE那么你可以写成

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 演示

于 2013-07-18T07:59:14.360 回答
1

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

SQL小提琴

于 2013-07-18T08:05:25.440 回答