SQL AVG(COUNT(*))?

时间:2009-04-29 00:05:05

标签: 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

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

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

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

由于

3 个答案:

答案 0 :(得分:2)

这应该适用于Oracle:

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

select avg(howmanytimes) from dvd_count_view;

答案 1 :(得分:2)

未经测试...

with 
loan_copy_total as 
(
    select dvdid, copyid, count(*) as cnt
    from loan
    group by dvdid, copyid
),
loan_copy_avg as
(
    select dvdid, avg(cnt) as copy_avg
    from loan_copy_total
    group by dvdid
)

select lct.*, lca.copy_avg
from loan_copy_avg lca
inner join loan_copy_total lct on lca.dvdid = lct.dvdid
    and lct.cnt <= lca.copy_avg; 

答案 2 :(得分:2)

与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;