且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

计算数据透视表内的标准偏差

更新时间:2023-02-05 08:06:35

我认为您唯一的问题是ELSE 0.您只需要NULL值,因为它们将被忽略:

I think your only problem is the ELSE 0. You simply want NULL values, because they will be ignored:

SELECT mid                                 as mID,
       round((x.qty_sum / x.qty_count), 5) as qtAVG,
       round(x.qty_stddev, 5)              as qtSTDDEV,
       x.qty_count                         as qtCOUNT,
       round((x.rel_sum / x.rel_count), 5) as relAVG,
       round(x.rel_stddev, 5)              as relSTDDEV,
       x.rel_count                         as relCOUNT,
FROM (SELECT mid,
             SUM( mt = 'qt' )   as qty_count,
             SUM(CASE WHEN mt = 'qt' THEN rt END)  as qty_sum,
             STD(CASE WHEN mt = 'qt' THEN rt END)  as qty_stddev,
             SUM( mt = 'rel' ) as rel_count,
             SUM(CASE WHEN mt = 'rel' THEN rel END) as rel_sum,
             STD(CASE WHEN mt = 'rel' THEN rel END) as rel_stddev
      FROM t_r
      GROUP BY mid
     ) x;

请注意其他一些更改:

  • 我简化了计数逻辑,以删除CASE表达式.它使用MySQL扩展,将布尔值视为数字,其中1为true,0为false.
  • 我用双引号替换了双引号.单引号是字符串的标准分隔符.
  • 我删除了ELSE子句.聚合函数会忽略NULL值,因此这应该可以解决您的问题.
  • I simplified the logic for the counts, to remove the CASE expression. This uses a MySQL extension that treats booleans as numbers with 1 for true and 0 for false.
  • I replaced the double quotes with single quotes. Single quotes are the standard delimiter for strings.
  • I removed the ELSE clauses. Aggregation functions ignore NULL values, so this should fix your problem.