2017-08-07 15 views
0

私は、値で指定された集計値を生成する必要があるシナリオを持っています。可能集計最小、最大、平均及びモード集計計算特定の列に基づいて

Table 

ColumnA ColumnB 
    A  Min 
    A  Mode 
    A   Avg 

    B  Max 
    B  Avg 

    C  Mode 
    C  Min 

    D   Avg 

Table 2 

    ColumnC ColumnD ColumnE 

    Pr1  1.00  A 
    Pr2  2.00  A 
    Pr3  3.00  A 

    Pr1  4.00  B 
    Pr2  5.00  B 
    Pr4  1.00  B 

    Pr5  2.00  C 
    Pr6  6.00  C 

    Pr7  4.00  D 
    Pr8  5.00  D 

表1に定義され、集計2.表にcolumnDに提供された値を用いるものとして集計を見つける必要がColumnAの各タイプ別にグループ化されます。私はストアドプロシージャの一部を追加したいと思います。ここで

Output should be 

    ColumnF ColumnG ColumnH 
    A  Min  1.00 
    A  Mode  1.00 (if no mode exists take min value) 
    A   Avg  2.00 

    B  Max  5.00 
    B  Avg  3.34 

    C  Mode  2.00 
    C  Min  2.00 

    D   Avg  4.50 
+0

これら2つのテーブルはどのように関連していますか?ここにユニークな結合キーはありません...そして、あなたは何を集約していますか? – scsimon

+0

表は列Aおよび列Eに関連しています – TechJump

答えて

0

は強引なソリューションです:

select t1.*, 
     (case when column_b = 'min' then min_d 
      when column_b = 'max' then max_d 
      when column_b = 'mode' then mode_d 
     end) as stat 
from t1 outer apply 
    (select min(d) as min_d, max(d) as max_d, avg(d) as avg_d, 
      (case when min(case when cnt = max_cnt then d end) = max(case when cnt = max_cnt then d end) 
        then max(case when cnt = max_cnt then d end) 
        else avg(d) 
       end) as mode_d 
     from (select t2.*, max(cnt) over() as max_cnt 
      from (select t2.*, count(*) over (partition by d) as cnt 
        from table2 t2 
       ) t2 
      ) t2 
    ) t2; 

mode計算は少しトリッキーですが、私はそれが何をしたいんだと思います。

関連する問題