聚合计算基于特定列

时间:2017-08-07 14:56:59

标签: sql stored-procedures sql-server-2012 aggregation

我有一个场景,需要生成由值指定的聚合值。可能的聚合Min,Max,Avg和Mode

a ~ c -> c -> c -> c

需要找到表1中定义的聚合,并使用表2中columnD中提供的值。聚合按每种类型的ColumnA分组。我想添加部分存储过程。

 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 个答案:

答案 0 :(得分: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计算有点棘手,但我认为它符合您的要求。