如何对 MYSQL 中的行子集的列求和
How to sum a column over a subset of rows in MYSQL
我希望我能以一种易于理解的方式描述我的问题。
所以我得到了一个 table 的记录事件,如下所示:
id
event
count
marker
1
EVENT 1
3
false
2
EVENT 1
2
false
3
EVENT 2
4
false
4
EVENT 1
1
true
5
EVENT 1
6
false
6
EVENT 1
2
true
7
EVENT 1
5
false
8
EVENT 2
3
true
9
EVENT 1
3
false
10
EVENT 2
5
false
我想要的是所有行的 'count' 列的总和,比每个事件不同的列标记中最后一次出现的 true 更新(更高的 id)。
我能够像这样单独获得每个事件的结果('event 1' 的示例):
select sum(count) from test_table
where event='EVENT 1'
and id > (select id from test_table
where event='EVENT 1'
and marker=1
order by id desc limit 1);
此查询的结果为 8(第 7 行和第 9 行的总和),'EVENT 2' 的查询结果分别为 5(第 10 行的总和)。
但现在我想像这样在一个查询中获得这些结果:
event
sum
EVENT 1
8
EVENT 2
5
这可能吗?我试了一下 window 函数,但没有得到想要的结果。
希望有人能帮助我。
您好
弗兰克
What i want is the sum of the column 'count' of all rows newer (higher id) than the last occurence of a true in the column marker distinct for every event.
一种方法是:
select event, sum(count)
from t
where id > (select max(t2.id) from t t2 where t2.event = t.event and marker)
group by event
我希望我能以一种易于理解的方式描述我的问题。
所以我得到了一个 table 的记录事件,如下所示:
id | event | count | marker |
---|---|---|---|
1 | EVENT 1 | 3 | false |
2 | EVENT 1 | 2 | false |
3 | EVENT 2 | 4 | false |
4 | EVENT 1 | 1 | true |
5 | EVENT 1 | 6 | false |
6 | EVENT 1 | 2 | true |
7 | EVENT 1 | 5 | false |
8 | EVENT 2 | 3 | true |
9 | EVENT 1 | 3 | false |
10 | EVENT 2 | 5 | false |
我想要的是所有行的 'count' 列的总和,比每个事件不同的列标记中最后一次出现的 true 更新(更高的 id)。
我能够像这样单独获得每个事件的结果('event 1' 的示例):
select sum(count) from test_table
where event='EVENT 1'
and id > (select id from test_table
where event='EVENT 1'
and marker=1
order by id desc limit 1);
此查询的结果为 8(第 7 行和第 9 行的总和),'EVENT 2' 的查询结果分别为 5(第 10 行的总和)。
但现在我想像这样在一个查询中获得这些结果:
event | sum |
---|---|
EVENT 1 | 8 |
EVENT 2 | 5 |
这可能吗?我试了一下 window 函数,但没有得到想要的结果。
希望有人能帮助我。
您好 弗兰克
What i want is the sum of the column 'count' of all rows newer (higher id) than the last occurence of a true in the column marker distinct for every event.
一种方法是:
select event, sum(count)
from t
where id > (select max(t2.id) from t t2 where t2.event = t.event and marker)
group by event