按行分组为多个组

group by rows into multiple groups

我有一个table

id    index   value
1       1        2
2       1        3 
3       2        6
4       3        8

我可以这样做:

select sum(value) from table group by index

但是我想要的是每一行可以去多个组,伪代码

 select sum(value) from table group by >= index

基本上索引是 1、2、3,我希望它将它们分成 3 个单独的组。

  1. 索引为 bigger/equal 比 1
  2. 的值的总和
  3. 索引为 bigger/equal 比 2
  4. 的值的总和
  5. 索引为 bigger/equal 比 3
  6. 的值的总和

这一定是一个通用函数,所以我实际上不知道索引级别,因为它是在这里硬编码的。

这是示例输出:

indexLevelBiggerEquals   sumValue
          1                 19          -- sum of all rows that are >= 1
          2                 14          -- sum of all rows that are >= 2
          3                 8           -- sum of all rows that are >= 3

每个 "index >" 组求和,用例选择要求和的值:

select sum(case when index >= 1 then value else 0 end) sum1,
       sum(case when index >= 2 then value else 0 end) sum2,
       sum(case when index >= 3 then value else 0 end) sum3
from table group by index

这可能是您想要的:

select index,
       (select sum(value) from table where index >= t1.index)
from (select distinct index from table) t1;

使用 window 函数,处理 table 的有限选择(请注意,选择默认为 UNBOUNDED PRECEDINGCURRENT ROW,这就是您想要的在这里,但您可以指定其他内容):

INSERT INTO tmp VALUES
(1,       1,        2),
(2,       1,        3),
(3,       2,        6),
(4,       3,        8)
;

SELECT index, SUM(value) OVER ( ORDER BY index DESC )
FROM tmp;


┌───────┬─────┐
│ index │ sum │
├───────┼─────┤
│     3 │   8 │
│     2 │  14 │
│     1 │  19 │
│     1 │  19 │
└───────┴─────┘
(4 rows)

编辑:

在查询中使用其他函数:

SELECT index,
       COUNT(index),
       SUM(SUM(value)) OVER ( ORDER BY index DESC )                                                                             
FROM tmp 
GROUP BY index;
┌───────┬───────┬─────┐
│ index │ count │ sum │
├───────┼───────┼─────┤
│     3 │     1 │   8 │
│     2 │     1 │  14 │
│     1 │     2 │  19 │
└───────┴───────┴─────┘
(3 rows)

SUM(SUM(value)) 是必需的,因为 value 必须出现在聚合函数中。请参阅 here 以获得更好的解释。