简体   繁体   English

SQL查询获取用户在页面上花费的平均时间

[英]SQL query to get the average time spent by user on page

Here is a sample table that I am using,这是我正在使用的示例表,

User_id           timestamp            action
1            2020-10-01 09:00:00    Opened page
1            2020-10-01 09:10:00    Closed page
2            2020-10-02 04:00:00    Signed up
3            2020-10-02 06:00:00    Opened page
3            2020-10-03 11:00:00    Made a booking
3            2020-10-03 09:30:00    Closed page

need to write a SQL query to find the average time spent by a user on the page.需要编写一个 SQL 查询来查找用户在页面上花费的平均时间。

The expected answer is just a number which represents the average time spent by an average user on the page.预期的答案只是一个数字,代表普通用户在页面上花费的平均时间。

You can't use SQL to calculate how much time a user spends on different pages of your UI application.您不能使用 SQL 来计算用户在 UI 应用程序的不同页面上花费的时间。 You will need to implement this logic on your UI whenever there is an event such as when the user navigates to another page or a button click etc. You capture the timestamps you need on the UI and then make a database call through an SP call or Query through your server side code (such as .Net, Java or Node.js).每当发生诸如用户导航到另一个页面或单击按钮等事件时,您都需要在 UI 上实现此逻辑。您在 UI 上捕获所需的时间戳,然后通过 SP 调用进行数据库调用或通过您的服务器端代码(例如 .Net、Java 或 Node.js)进行查询。

Once you have captured the data from the UI you will be able to implement any kind of logic on that data through an SP or a function or something like that in using SQL.从 UI 捕获数据后,您将能够通过 SP 或函数或类似使用 SQL 的东西对该数据实施任何类型的逻辑。

If you use TIMESTAMPDIFF() , and set its argument to SECOND , you can get back the difference of two datetime fields in a record in a manner that can be summed and divided.如果您使用TIMESTAMPDIFF() ,并将其参数设置为SECOND ,您可以以可以求和和除法的方式取回记录中两个日期时间字段的差异。 Documentation:文档:

Returns datetime_expr2 − datetime_expr1, where datetime_expr1 and datetime_expr2 are date or datetime expressions.返回 datetime_expr2 - datetime_expr1,其中 datetime_expr1 和 datetime_expr2 是日期或日期时间表达式。

Then use SUM() to sum up these values, and divide by the results of COUNT() .然后使用SUM()将这些值相加,并除以COUNT()的结果。 Documentation:文档:

SUM() : Returns the sum of expr. SUM() :返回 expr 的总和。 If the return set has no rows, SUM() returns NULL.如果返回集没有行,则 SUM() 返回 NULL。 COUNT() : Returns a count of the number of non-NULL values of expr in the rows retrieved by a SELECT statement. COUNT() :返回由 SELECT 语句检索的行中 expr 的非 NULL 值的数量的计数。

Your code will then basically look like this.您的代码将基本上如下所示。 You may need to make some adjustments based on your database setup.您可能需要根据您的数据库设置进行一些调整。

SELECT
    SUM(
        TIMESTAMPDIFF(SECOND, OrigDateTime, LastDateTime)
    ) / (select COUNT(id) FROM yourTable)
    AS average
FROM yourTable;

This, of course, follows our standard formula for calculating an average:当然,这遵循我们计算平均值的标准公式:

sum(differences) / count(differences)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM