SQL AVG(COUNT(*))?

6 sql oracle aggregate-functions

我试图找出值在列中出现的平均次数,根据另一列对其进行分组,然后对其进行计算.

我有3张桌子,有点像这样

DVD

ID | NAME
1  | 1       
2  | 1     
3  | 2      
4  | 3

COPY 

ID | DVDID   
1  | 1  
2  | 1  
3  | 2  
4  | 3  
5  | 1

LOAN

ID | DVDID | COPYID  
1  | 1     |  1  
2  | 1     |  2  
3  | 2     |  3    
4  | 3     |  4  
5  | 1     |  5
6  | 1     |  5
7  | 1     |  5
8  | 1     |  2
Run Code Online (Sandbox Code Playgroud)

等等

基本上,我试图找到贷款表中出现的所有副本ID少于该DVD所有副本的平均次数.

所以在上面的例子中,dvd 1的副本5出现3次,副本2出现两次并复制1次,因此该DVD的平均值为2.我想列出那个(和另一个)dvd的所有副本贷款表中的那个数字.

我希望这更有意义......

谢谢

Dav*_*sta 5

类似于 dotjoe 的解决方案,但使用解析函数来避免额外的连接。可能或多或少有效率。

with 
loan_copy_total as 
(
    select dvdid, copyid, count(*) as cnt
    from loan
    group by dvdid, copyid
),
loan_copy_avg as
(
    select dvdid, copyid, cnt, avg(cnt) over (partition by dvdid) as copy_avg
    from loan_copy_total
)
select *
from loan_copy_avg lca
where cnt <= copy_avg;
Run Code Online (Sandbox Code Playgroud)


Pab*_*ruz 3

这应该适用于 Oracle:

create view dvd_count_view
select dvdid, count(1) as howmanytimes
  from loans
 group by dvdid;

select avg(howmanytimes) from dvd_count_view;
Run Code Online (Sandbox Code Playgroud)