简体   繁体   English

如何编辑此MySQL查询以包括带有count和avg的额外列?

[英]How to edit this MySQL query to include an extra column with count and avg?

This query: 该查询:

select p.visitor_id , p.url, avg(p.duration), count(*) as sum_pages
from pages p
where visitor_id = 1
group by p.visitor_id , p.url
having avg(p.duration) > (select avg(p2.duration)
                          from pages p2
                          where p2.visitor_id = p.visitor_id
                         );

produces this hypothetical table: 产生此假设表:

visitor_id ---- url ---- duration --- sum_pages
1 ------------ home ------- 5 ------- 20
1 ------------ about ------ 8 ------- 12
1 ------------ contact ---- 2 ------- 13
1 ------------ services --- 2 ------- 18

What it does: Takes the average duration number of the whole table, and checks if the average duration URL is greater. 它的作用:获取整个表的平均持续时间数,并检查平均持续时间URL是否更大。 If yes, it displays the number. 如果是,则显示数字。

I want to do the same thing and this time to add the pageviews. 我想做同样的事情,这次添加页面浏览量。 Each row is counted as a pageview. 每行都计为一次网页浏览。

How do I achieve this? 我该如何实现?

I found a way to achieve this but not sure about the performance of the query: 我找到了一种方法来实现此目的,但不确定查询的性能:

select
visitor_id, 
url,
sum(duration), 
avg(duration),
count(*) as sum_pages
from pages p 
where visitor_id='1' 
group by visitor_id,url
having sum(duration) > (select avg(duration)
                         from pages
                         where visitor_id=p.visitor_id
                       )
 and sum_pages > (select count(*)/(select count(distinct url) from pages where visitor_id=p1.visitor_id)
                   from pages p1
                  where p1.visitor_id=p.visitor_id
                  )
 ;    

DEMO 演示

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

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