简体   繁体   中英

How to sum same rows and find those that are above average in mySQL?

This is a sample of my database table:

visitor_id ---- url ---- duration
1 ------------ home ------- 5
1 ------------ about ------ 8
1 ------------ about ------ 3
1 ------------ contact ---- 2
1 ------------ home ------- 3
1 ------------ services --- 2

What I want to achieve is to show the urls that are more than the average of all urls. But first I need to sum the duration group by url.

For example, the average of all pages = 5+8+3+2+3 + 2 = 23 / 6 = 3.8

So the pages that will be shown is home ( 8 secs) and about (11).

How can I achieve this?

This is what I have so far

select sum(duration), url from pages where visitor_id='1' group by url

You can join in the average or use a having clause. I would write this as:

select p.visitor_id, p.url, avg(p.duration)
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
                         );

Notes:

  • I'm guessing that visitor_id is numeric, so the constant is a number instead of a string.
  • The subquery in the having clause is correlated to the outer query, so the visitor id is input only once.
  • The query aggregates by both visitor id and url, so it will work for any number (or all) visitors.

You could use an having on subquery for avg

  select sum(duration) sum_dur, url 
  from pages 
  where visitor_id='1' 
  group by url 
  having sum_dur > (
  select avg(duration)  
  from  pages 
  where visitor_id='1' 
  )

Try this:

Select url
,visitor_id
,duration
From (
select url
,visitor_id
,sum(duration) as duration
,avg(duration) over (partition by visitor_id) as avg_by_visitor_id
from pages
group by url
,visitor_id
,duration) as data
where data.avg_by_visitor_id<=data.duration

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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