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

基本的に、貸し出しテーブルに表示されるすべてのコピー ID を、その DVD のすべてのコピーの平均回数より少ない回数で見つけようとしています。

上記の例では、DVD 1 のコピー 5 が 3 回表示され、コピー 2 が 2 回表示され、コピー 1 が 1 回表示されるため、その DVD の平均は 2 です。 Loan テーブルのその番号。

それがもう少し理にかなっていることを願っています...

ありがとう

4

3 に答える 3

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;
于 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 に答える