用sql求2018年4月每个时段的,pv、uv 数量、按照uv转化率取top5. -- uv 转化率 = 转化人数/uv数量 ,假设现在转化人数是 1
时间: 2023-07-15 18:15:33 浏览: 140
假设有如下表结构:
|字段名|类型|
|---|---|
|id|int|
|timestamp|datetime|
|pv|int|
|uv|int|
则可以使用如下 SQL 语句求得 2018 年 4 月每个时段的 pv、uv 数量:
```
SELECT DATE_FORMAT(timestamp, '%Y-%m-%d %H') AS hour, SUM(pv) AS pv_count, SUM(uv) AS uv_count
FROM table_name
WHERE YEAR(timestamp) = 2018 AND MONTH(timestamp) = 4
GROUP BY DATE_FORMAT(timestamp, '%Y-%m-%d %H')
ORDER BY hour ASC;
```
为了计算 uv 转化率并取 top5,可以在上述 SQL 语句的基础上添加子查询和计算语句:
```
SELECT sub.hour, sub.pv_count, sub.uv_count, sub.conversion_rate
FROM (
SELECT DATE_FORMAT(timestamp, '%Y-%m-%d %H') AS hour, SUM(pv) AS pv_count, SUM(uv) AS uv_count,
IF(SUM(uv) = 0, 0, 1/SUM(uv)) AS conversion_rate
FROM table_name
WHERE YEAR(timestamp) = 2018 AND MONTH(timestamp) = 4
GROUP BY DATE_FORMAT(timestamp, '%Y-%m-%d %H')
) AS sub
ORDER BY sub.conversion_rate DESC
LIMIT 5;
```
上述 SQL 语句中的子查询计算了每个时段的 pv、uv 数量和转化率,并将结果按转化率降序排列,最后取 top5。其中,IF 函数用于避免除数为 0 的情况。
阅读全文