【问题标题】:Choosing 10 largest sets of data based on sum, outputting cumulative sum for each根据总和选择最大的10组数据,输出每组的累积总和
【发布时间】:2020-09-08 15:57:39
【问题描述】:

假设数据集是:

Class    Value    Ordering
A        10       1
A        13       2
...
B        20       1
B        7        2
...

我希望能够找到总价值最高的10个班级,然后输出每个班级的累计总和。

到目前为止,我已经创建了一个脚本来确定最大的 10 个:

SELECT Class
FROM Table
GROUP BY Class
ORDER BY sum(Value) DESC
LIMIT 10;

以及一个查找特定类的累积和的脚本:

SELECT sum(Value) OVER (
       ORDER BY Ordering
       ROWS BETWEEN
           UNBOUNDED PRECEDING
           AND CURRENT ROW
       ) AS cumulativeSum
FROM Table
WHERE Class = 'A'
ORDER BY Ordering ASC;

但我找不到将过程组合在一起的方法

编辑:

假设 A 和 B 是两个最高的类,输出将是:

A    B
10   20
23   27

如果 C 类不是 10 个最大的类之一,则不会输出

【问题讨论】:

    标签: sql database sqlite sum window-functions


    【解决方案1】:

    如果我正确地跟随你,你可以这样做:

    select class, value, ordering, cumulativeSum
    from (
        select
            t.*,
            rank() over(order by totalsum desc) rn
        from (
            select 
                t.*, 
                sum(value) over(partition by class order by ordering) cumulativeSum,
                sum(value) over(partition by class) totalsum
            from table t
        ) t
    ) t
    where rn <= 10
    order by class, ordering
    

    这会根据 value 的总数过滤前 10 个 classes 的表格,并将每个 class 的累积总和添加到每一行。

    【讨论】:

      猜你喜欢
      • 2020-04-04
      • 1970-01-01
      • 2020-10-16
      • 1970-01-01
      • 2015-09-11
      • 2020-11-28
      • 1970-01-01
      • 2021-06-18
      • 1970-01-01
      相关资源
      最近更新 更多