分组后反转列值

时间:2019-04-29 01:44:30

标签: postgresql group-by

我有一张桌子,如下表

id    |      group  |   value
------+-------------+----------
 1    |        1    |     2
 2    |        1    |     4     
 3    |        1    |     3
 4    |        2    |     2
 5    |        2    |     9
 6    |        2    |     5

我想按“ id”的顺序按“ group”对行进行分组,并创建一个新列,按如下所示反转“ value”列

id    |      group  |   value |   reversedvalue
------+-------------+---------+---------
 1    |        1    |     2   |      3  
 2    |        1    |     4   |      4  
 3    |        1    |     3   |      2
 4    |        2    |     2   |      5
 5    |        2    |     9   |      9
 6    |        2    |     5   |      2

1 个答案:

答案 0 :(得分:0)

尝试以下操作:

SELECT q1.id,q1.group_id,q1.value,q2.value
FROM
    (
        SELECT *,ROW_NUMBER()OVER(PARTITION BY group_id ORDER BY id) n
        FROM your_table
    ) q1
JOIN
    (
        SELECT *,ROW_NUMBER()OVER(PARTITION BY group_id ORDER BY id DESC) n
        FROM your_table
    ) q2
ON q1.group_id=q2.group_id AND q1.n=q2.n

您也可以使用CTE

WITH cte AS(
    SELECT *,
        ROW_NUMBER()OVER(PARTITION BY group_id ORDER BY id) n1,
        ROW_NUMBER()OVER(PARTITION BY group_id ORDER BY id DESC) n2
    FROM your_table
)
SELECT q1.id,q1.group_id,q1.value,q2.value
FROM
    cte q1
JOIN
    cte q2
ON q1.group_id=q2.group_id AND q1.n1=q2.n2;