如何根据日期计算查询中的总计?
how can I calculate totals within a query, depending on the date?
您可以在下面看到我的查询,结果如下:
select t.actual_date,
t.id_key,
t.attendance_status,
t.money_step,
sum(t.money_step) over (partition by t.id_key order by t.actual_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)as accumulated
from example t
order by t.id_key, t.actual_date
我希望 "accumulated" 列为每个 id_key 添加 "money_step" 的值。
如果 attendance_status 是 Id 的第二次“15”,则计数器应从头开始累加。对于 ID_KEY = 1,它应该如下所示:
累计:
Row 1:20
Row 2: 80
Row 3: 100
Row 4: 120
如何在查询中执行此操作?有人可以帮助我吗?
我了解到您想在第一行 attendance_status
的值为 15
之后重置总和。一个选项使用条件 max()
来定义子组:
select
actual_date,
id_key,
attendance_status,
money_step,
sum(t.money_step) over (
partition by id_key, grp
order by actual_date
) as accumulated
from (
select
e.*,
max(case when attendance_status = 15 then 1 else 0 end) over(
partition by id_key
order by actual_date
rows between unbounded preceding and 1 preceding
) grp
from example e
) e
order by id_key, actual_date
您可以在下面看到我的查询,结果如下:
select t.actual_date,
t.id_key,
t.attendance_status,
t.money_step,
sum(t.money_step) over (partition by t.id_key order by t.actual_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)as accumulated
from example t
order by t.id_key, t.actual_date
我希望 "accumulated" 列为每个 id_key 添加 "money_step" 的值。 如果 attendance_status 是 Id 的第二次“15”,则计数器应从头开始累加。对于 ID_KEY = 1,它应该如下所示:
累计:
Row 1:20
Row 2: 80
Row 3: 100
Row 4: 120
如何在查询中执行此操作?有人可以帮助我吗?
我了解到您想在第一行 attendance_status
的值为 15
之后重置总和。一个选项使用条件 max()
来定义子组:
select
actual_date,
id_key,
attendance_status,
money_step,
sum(t.money_step) over (
partition by id_key, grp
order by actual_date
) as accumulated
from (
select
e.*,
max(case when attendance_status = 15 then 1 else 0 end) over(
partition by id_key
order by actual_date
rows between unbounded preceding and 1 preceding
) grp
from example e
) e
order by id_key, actual_date