如何反转列的顺序

时间:2016-12-20 12:01:26

标签: sql sql-server database

我有一张下表:

ps aux

我想只反转Y列的顺序而不影响其余的数据。
输出应该如下:

X   Y   Z
-----------
1   10  100
2   20  200
3   30  300
4   40  400

有人可以帮帮我吗?

2 个答案:

答案 0 :(得分:0)

检查这个。

            select b.X,a.Y,b.Z from
            (
            select X,   Y,Z, ROW_NUMBER() OVER(ORDER BY Y DESC) as rnk1
            from #tableName 
            )a 
            inner join
            (
            select X,Y,Z,ROW_NUMBER() OVER(ORDER BY Y)aa
            from #tableName t 
            )b
            on a.rnk1=b.aa

OR

            select X,50-Y ,Z from
            #tableName t1 
  

OutPut:

enter image description here

答案 1 :(得分:-1)

以下是适合您的SQL Server解决方案:

DECLARE @table TABLE (x INT, y INT, z INT);
INSERT INTO @table SELECT 1, 10, 100;
INSERT INTO @table SELECT 2, 20, 200;
INSERT INTO @table SELECT 3, 30, 300;
INSERT INTO @table SELECT 4, 40, 400;
WITH Reversed AS (
    SELECT
        x,
        ROW_NUMBER() OVER (ORDER BY x) AS r1,
        ROW_NUMBER() OVER (ORDER BY x DESC) AS r2
    FROM
        @table)
SELECT
    t1.x,
    t2.y,
    t1.z
FROM
    Reversed r
    INNER JOIN @table t1 ON t1.x = r.r1
    INNER JOIN @table t2 ON t2.x = r.r2
ORDER BY
    t1.x;