8

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

我有 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

ETC

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

所以在上面的例子中,dvd 1 的副本 5 出现 3 次,复制 2 两次,然后复制 1 一次,所以该 DVD 的平均值是 2。我想列出出现少于贷款表中的那个数字。

我希望这更有意义...

谢谢

4

3 回答 3

5

Similar to dotjoe's solution, but using an analytic function to avoid the extra join. May be more or less efficient.

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;
于 2009-04-30T15:10:06.487 回答
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;
于 2009-04-29T00:14:14.260 回答
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; 
于 2009-04-29T03:40:25.653 回答