【问题标题】:Aggregate Calculations Based on specific columns基于特定列的聚合计算
【发布时间】:2018-01-14 22:32:53
【问题描述】:

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

 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

【问题讨论】:

  • 这两个表有什么关系?这里没有唯一的连接键...您要汇总什么?
  • 表格与A列和E列相关

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


【解决方案1】:

这是一个蛮力解决方案:

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 的计算有点棘手,但我认为它可以满足您的需求。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-22
    • 1970-01-01
    • 1970-01-01
    • 2016-11-03
    • 1970-01-01
    • 2015-05-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多