【问题标题】:How to create a cumulative sum grouped by column如何创建按列分组的累积总和
【发布时间】:2020-11-03 00:35:29
【问题描述】:

我有一个表格,其中有两列或多列代表状态

╔════════════╤═══════════╤═══════════╗
║ updated_at │ state_one │ state_two ║
╠════════════╪═══════════╪═══════════╣
║ 12/31/1999 │ 1         │ 2         ║
╟────────────┼───────────┼───────────╢
║ 1/1/2000   │ 2         │ 3         ║
╟────────────┼───────────┼───────────╢
║ 1/2/2000   │ 0         │ 3         ║
╚════════════╧═══════════╧═══════════╝

我希望能够编写一个简单的查询来计算状态列state_onestate_two 处于给定状态的每一行的累积总和。一个给我类似的查询:

╔════════════╤═══════════╤═══════════╤══════════════════════╤══════════════════════╗
║ updated_at │ state_one │ state_two │ cumulative_sum_one_1 │ cumulative_sum_two_2 ║
╠════════════╪═══════════╪═══════════╪══════════════════════╪══════════════════════╣
║ 12/31/1999 │ 1         │ 2         │ 1                    │ 1                    ║
╟────────────┼───────────┼───────────┼──────────────────────┼──────────────────────╢
║ 1/1/2000   │ 2         │ 2         │ 1                    │ 2                    ║
╟────────────┼───────────┼───────────┼──────────────────────┼──────────────────────╢
║ 1/2/2000   │ 0         │ 1         │ 1                    │ 2                    ║
╚════════════╧═══════════╧═══════════╧══════════════════════╧══════════════════════╝

会有更多的列,但是会有更多的列,因为有更多的州。

我正在使用 MySQL 5.6.35 版本。虽然我知道我做错了,但这是我到目前为止的查询,但它计算所有行的累积总和:

select
    row.day,
    case row.state when 1 then "foo"
                   when 2 then "bar"
                   else "baz"
    end as state,
    row.state_count,
    @running_total:= (
        @running_total + row.state_count
     ) as cumulative_sum
from (
    select
        date_format(from_unixtime(updated_at), '%m/%d/%Y') as day,
        count(state) as state_count,
        state
    from 
        table_of_interest
    group by day
) row
join (select @running_total:=0) r
order by row.day

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

    您可以使用相关子查询:

    select t.*,
           (select count(*)
            from table_of_interest t2
            where t2.update_at <= t.updated_at and t2.state_one = 1
           ) as cumulative_sum_one_1,
           (select count(*)
            from table_of_interest t2
            where t2.update_at <= t.updated_at and t2.state_one = 2
           ) as cumulative_sum_two_2
    from table_of_interest t;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-11
      • 2014-04-12
      • 2020-04-04
      • 2020-12-23
      • 2018-01-16
      • 2019-12-01
      相关资源
      最近更新 更多