【问题标题】:group by rows into multiple groups按行分组为多个组
【发布时间】:2023-03-14 11:51:01
【问题描述】:

我有一张桌子

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. 索引大于/等于 1 的值的总和
  2. 索引大于/等于 2 的值的总和
  3. 索引大于/等于 3 的值的总和

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

这是示例输出:

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

【问题讨论】:

  • sum(index >= 1 then value else 0 end) ...
  • 你能添加一个实际输出应该是什么样子的例子吗?您希望所有这些都放在不同的列中吗?
  • @a_horse_with_no_name 添加示例输出
  • 那么 Marth 的答案正是您想要的。

标签: sql postgresql group-by


【解决方案1】:

每个“索引>”组一个总和,用例选择要求和的值:

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;

【讨论】:

  • 这必须是一个通用函数,所以我实际上不会知道索引级别。索引可能是 1,5,50,500
  • 如何“输入”索引?
  • 索引是数据库中的列,如您所见,在当前数据中,索引值为1,2,3。它应该按索引分组,但不等于,而是 >=.
  • 对,您需要加入。敬请期待!
【解决方案2】:

使用窗口函数,处理有限的表格选择(注意选择默认为 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 以获得更好的解释。

【讨论】:

  • 您需要另一个 order by index desc 来进行实际查询,以确保您获得该结果 - 但除此之外,我认为这是一个绝妙的技巧!
  • 为什么有 2 行索引为 1?
  • @Jaanus :如果您不希望多行具有相同的索引,请使用 SELECT DISTINCT ON (index)。至于为什么,窗口函数不会在最终结果中将行组合在一起(不像GROUP BY)。
  • 如何使用count()等其他功能,我想计算每个组的增长?我尝试使用count(index),但它说index must appear in the GROUP BY clause
  • @Jaanus :编辑了我的答案。不确定你所说的“成长”是什么意思,但我添加了一个关于如何使用 COUNT() 函数的示例。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多