【发布时间】: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
【问题讨论】: