题目一: sql: 计算下表的用户平均停留时长: || userid || actionType || timestamp || =============================== || a || login || 1234567891 || || a || logout || 1234567892 || || b || login || 1234567893 || || a || login || 1234567894 || || b || logout || 1234567895 || || a || logout || 1234567896 || 题目二: sql: 计算用户每人每天的最后一次登录微信的停留时长: the_date,uid,timestamp,stay_time 例子: 20210329,user123,1617012000,600
时间: 2023-08-03 12:04:25 浏览: 144
数据说明: 姓名|网址|访问时间 需求:分别计算每个用户在页面的停留时长。写入MySQL。 结果数据: 用户 网址 停留时长
题目一的SQL查询语句可以如下所示:
```sql
SELECT userid, AVG(stay_time) AS avg_stay_time
FROM (
SELECT userid, timestamp AS login_time,
LEAD(timestamp) OVER (PARTITION BY userid ORDER BY timestamp) AS logout_time,
LEAD(timestamp) OVER (PARTITION BY userid ORDER BY timestamp) - timestamp AS stay_time
FROM your_table
WHERE actionType = 'login'
) subquery
WHERE logout_time IS NOT NULL
GROUP BY userid;
```
注意替换 `your_table` 为你的表名。
题目二的SQL查询语句可以如下所示:
```sql
SELECT the_date, uid, stay_time
FROM (
SELECT the_date, uid, timestamp, stay_time,
ROW_NUMBER() OVER (PARTITION BY the_date, uid ORDER BY timestamp DESC) AS rn
FROM your_table
) subquery
WHERE rn = 1;
```
注意替换 `your_table` 为你的表名。
阅读全文