2017-08-07 91 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

这两张表如何关联?这里没有唯一的连接键......你在做什么? – 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计算是有点棘手,但我认为你想要做什么。