我有一个如下表。
我实际上是在2种情况下尝试选择汇总报告。
+---------------------+---------------+-----------------+
| timestamp | user | open_pages |
+---------------------+---------------+-----------------+
| 2018-09-19 12:27:02 | user1 | 66 |
| 2018-09-19 12:27:02 | user2 | 24 |
| 2018-09-19 12:27:10 | user2 | 24 |
| 2018-09-19 12:28:30 | user1 | 21 |
| 2018-09-19 12:28:30 | user2 | 20 |
| 2018-09-19 12:28:35 | user1 | 17 |
| 2018-09-19 12:28:35 | user2 | 11 |
| 2018-09-19 12:29:08 | user1 | 8 |
| 2018-09-19 12:29:08 | user2 | 8 |
| 2018-09-19 12:30:02 | user1 | 7 |
| 2018-09-19 12:30:02 | user2 | 6 |
+---------------------+---------------+-----------------+
示例输出:
+--------+-------+------------+
| minute | User | Open_pages |
+--------+-------+------------+
| 27 | User1 | 66 |
| 27 | User2 | 26 |
| 28 | user1 | 56 |
| 28 | user2 | 51 |
| 29 | user1 | 21 |
| 29 | user2 | 28 |
+--------+-------+------------+
我尝试了此查询,但是它没有显示正确的值。
select minute(timestamp), user, avg(open_pages)
from tbl where DATE(timestamp)= '2018-09-19'
group by minute(timestamp) order by 1;
在 12:27:02 ,用户2连接了两次并完全打开了 48页。所以他在27分钟后的打开页面数最高。这样,我想每分钟计算一次。
我不知道如何为此生成查询。
有人可以帮我解决这两个查询吗?
答案 0 :(得分:0)
给定小时内,每分钟/每用户平均打开页面的次数。
ts=timestamp, un=username, op=openpges
Select minute(op.ts) as mm, un, cast(avg(op) as int) as avgop
From openpages op
Where (op.ts between '2018-09-19 12:00:00' and '2018-09-19 12:59:59.999')
Group By minute(op.ts), un
Order By op.ts
此查询每个给定小时的open_pages之和。它使每个用户可见,但我不知道您如何每分钟只能选择一个特定行。也许最容易在应用程序端执行,每分钟使用第一行?
Select minute(op.ts) as mm, un, sum(op) as sumop
From openpages op
Where (op.ts between '2018-09-19 12:00:00' and '2018-09-19 12:59:59.999')
Group By minute(op.ts), un
Order By sumop desc
如果必须在应用程序端进行最终过滤,则可以将SUM和AVG放在同一查询中。这个查询足以给出两个答案。
Select minute(op.ts) as mm, un, sum(op) as sumop
, cast(avg(op) as int) as avgop
From openpages op
Where (op.ts between '2018-09-19 12:00:00' and '2018-09-19 12:59:59.999')
Group By minute(op.ts), un
Order By sumop desc
编辑,我不得不花一些时间解决这个问题,因为这是个人利益。我认为此查询可以为您提供每给定小时数内open_pages最大的用户列表。必须使用派生的临时表,正在运行的@variable并根据该变量进行顶层过滤。
set @mm=-1;
Select
CASE WHEN @mm=aTemp.mm THEN 0
ELSE 1
END as rn,
@mm:=aTemp.mm as mm,
aTemp.un, aTemp.sumop
From (
Select minute(op.ts) as mm, un, sum(op) as sumop
From openpages op
Where (op.ts between '2018-09-19 12:00:00' and '2018-09-19 12:59:59.999')
Group By minute(op.ts), un
Order By sumop desc
) aTemp
Having rn=1