如何创建按列分组的累积总和
Posted
技术标签:
【中文标题】如何创建按列分组的累积总和【英文标题】: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_one
和state_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
【问题讨论】:
【参考方案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;
【讨论】:
以上是关于如何创建按列分组的累积总和的主要内容,如果未能解决你的问题,请参考以下文章