计算AVG;输出高于平均水平的那些

时间:2018-11-19 02:36:31

标签: postgresql

查找来自的艺术家发行的所有现场专辑 CA(加拿大),并且其评级高于同年发行的所有专辑(任何类型,任何艺术家的专辑)的平均评级。对于每张满足要求的专辑,请按顺序输出其标题,艺术家的姓名和年份。

1 个答案:

答案 0 :(得分:1)

使用窗口函数执行此操作:

select t.album, t.name artist, t.year 
  from (
    select b.name album, a.name, b.year, b.ratings, avg(b.ratings) over (partition by b.year) year_rat
      from albums b, artists a, countries c
     where a.country=c.code
       and c.code='CA1'
       and a.name=b.artist
 ) t
 where t.ratings >= t.year_rat

或者,如果不使用任何窗口功能:

select albums.title, artists.name, albums.year
  from artists 
  join albums on albums.artist= artists.name
  join (select year, avg(ratings) avg_ratings from albums group by year) As temp 
    on temp.year=albums.year
 where artists.country='CA1'
   and albums.ratings >= temp.avg_ratings