如何确定使用一个非唯一的ID和时间戳列来计算总时间花费?

huangapple go评论61阅读模式
英文:

how do you determine the total time spend using an ID (that is not unique) and timestamp column?

问题

我尝试了以下方法来获取该访问者的总停留时间,但我无法使其工作。 event_time是时间戳,visit_id是ID(不是唯一的,会多次出现)。

SELECT
visit_id,
SUM(DATEDIFF(second, LAG(event_time) OVER (PARTITION BY visit_id ORDER BY event_time), event_time)) AS total_time_spent
FROM events_over
GROUP BY visit_id;

当我尝试运行此查询时,我看到以下错误:

窗口函数 [LAG(EVENTS.EVENT_TIME) OVER (PARTITION BY EVENTS.VISIT_ID ORDER BY EVENTS.EVENT_TIME ASC NULLS LAST)] 不能出现在聚合函数内部。

英文:

I've tried the following to get the total time spent for that visitor, but I'm unable to get this to work. Event_time is the timestamp and visit_id is the ID (which is not unique and will populate multiple times).

SELECT
visit_id,
SUM(DATEDIFF(second, LAG(event_time) OVER (PARTITION BY visit_id ORDER BY event_time), event_time)) AS total_time_spent
FROM events_over;
GROUP BY visit_id;

when I try to run this, I see the following error:

> Window function [LAG(EVENTS.EVENT_TIME) OVER (PARTITION BY
> EVENTS.VISIT_ID ORDER BY EVENTS.EVENT_TIME ASC NULLS LAST)] may not
> appear inside an aggregate function.

答案1

得分: 0

你不能在聚合函数内使用窗口函数,正如消息所示。以下的查询应该可以工作:

SELECT visit_id, SUM(time_diff) as total_time_spent FROM (
SELECT
visit_id,
DATEDIFF(second, LAG(event_time) OVER (PARTITION BY visit_id ORDER BY event_time), event_time) time_diff
FROM events_over )
GROUP BY visit_id;
英文:

You can't use a window function inside an aggregate function as the message says. This one should work:

SELECT visit_id, SUM(time_diff) as total_time_spent FROM (
SELECT
visit_id,
DATEDIFF(second, LAG(event_time) OVER (PARTITION BY visit_id ORDER BY event_time), event_time) time_diff
FROM events_over )
GROUP BY visit_id;

huangapple
  • 本文由 发表于 2023年2月24日 08:19:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/75551574.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定