总和列,但每一行

时间:2018-10-11 00:36:04

标签: sql postgresql

操作方式

this

我想得到

这样的结果

this

我已经尝试过的是这样的

select no, student, sum(point) from student group by no, student

但是结果与我预期的不一样。

1 个答案:

答案 0 :(得分:0)

您似乎想要“累计”,例如

select
     no
   , student
   , sum(point) over(partition by student order by no) run_sum
from student

看来,加分可能是像这样从决赛中减去倒数第二个总和。

WITH cte
AS (
    SELECT
        no
      , student
      , SUM(point) OVER (PARTITION BY student ORDER BY no) run_sum
      , ROW_NUMBER() OVER (PARTITION BY student ORDER BY no DESC) rn
    FROM student)
SELECT
    t.*
  , coalesce(t.rum_sum,0) - coalesce(ex.run_sum,0) AS extra_point
FROM cte t
LEFT JOIN (
    SELECT
        *
    FROM cte
    WHERE rn = 2) ex ON t.student = ex.student
                        AND t.rn = 1
                        AND ex.rn = 2
;

但没有更多关于Extra_point所需逻辑的指导,这只是一个猜测。