我有一个表格,按执行顺序列出活动及其持续时间,即表格按时间排序。它主要有四列:
person_ID、duration、activity_ID、time
如何将持续时间相加,直到达到某个 activity_ID?activity_ID 描述的活动可以按任何顺序出现。
例如,该表可以列出您白天的活动,例如起床、淋浴、刮胡子、吃饭、穿衣、穿鞋。顺序和活动因人和天而异。
我想总结所有活动的持续时间,直到某个活动(例如“穿衣服”)然后停止。我如何在 sql 中执行此操作?
问问题
1349 次
2 回答
1
不确定这是否是您要查找的内容,而是一种通用技术:根据您是否要包含它来打开或关闭一行的标志,然后将所有带有该标志的记录相加。
create table activity( person_ID number, duration number, activity_ID number)
insert into activity values(1, 1, 1);
insert into activity values(1, 2, 2);
insert into activity values(1, 3, 3);
insert into activity values(1, 4, 4);
insert into activity values(1, 5, 5);
insert into activity values(2, 10, 1);
insert into activity values(2, 20, 2);
insert into activity values(2, 30, 3);
insert into activity values(2, 40, 4);
insert into activity values(2, 50, 5);
SELECT person_id, SUM( CASE WHEN activity_id <= 3 THEN duration ELSE 0 END ) AS sum_till_3
FROM activity
GROUP BY person_id
ORDER BY person_id
PERSON_ID SUM_TILL_3
--------- ----------
1 6
2 60
于 2012-07-23T12:06:51.243 回答
0
以下是使用常规窗口函数的方法:
select t.user_id, sum(time <= activity_time then duration else 0 end)
from (select t.*,
min(activitytime) over (partition by user_id) as activitytime
from (select t.*,
(case when activity_id = xxx then 1 else 0 end) as isactivity,
(case when activity_id = xxx then time end) as activitytime,
from t
) t
) t
group by user_id
这只是找到每个用户发生活动的最短时间,然后将他们的持续时间相加。
于 2012-07-23T13:26:50.713 回答