计算透视表内的标准偏差

yc0p9oo0  于 2021-06-17  发布在  Mysql
关注(0)|答案(2)|浏览(361)

我有一个pivot查询,如下所示 count 以及 AVG 行,但不是标准差, STD .
如何修改下面的sql以获得 STD ?

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(CASE WHEN (mt = "qt") THEN 1 ELSE 0 END)   as qty_count,
         SUM(CASE WHEN (mt = "qt") THEN rt ELSE 0 END)  as qty_sum,
         STD(CASE WHEN (mt = "qt") THEN rt ELSE 0 END)  as qty_stddev
         SUM(CASE WHEN (mt = "rel") THEN 1 ELSE 0 END)  as rel_count,
         SUM(CASE WHEN (mt = "rel") THEN rel ELSE 0 END) as rel_sum,
         STD(CASE WHEN (mt = "rel") THEN rel ELSE 0 END) as rel_stddev
  FROM t_r
  GROUP BY mid) x;
edqdpe6u

edqdpe6u1#

似乎你想在子查询方面胜过mysql。至于关注点,您不需要这种额外的复杂性,只需使用一个简单的聚合查询,其中包含一个where子句,用于过滤具有mt=“qt”的记录。

SELECT 
    mid as mID,
    ROUND(AVG(rt), 5) as qtAVG,
    ROUND(STD(rt), 5) as qtSTDDEV,
    COUNT(*) as qtCOUNT,
FROM t_r
WHERE mt =  "qt"
GROUP BY mt
6tqwzwtp

6tqwzwtp2#

我想你唯一的问题是 ELSE 0 . 你只是想 NULL 值,因为它们将被忽略:

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 为了真实和 0 为假。
我用单引号代替了双引号。单引号是字符串的标准分隔符。
我移除了 ELSE 条款。聚合函数忽略 NULL 值,所以这应该可以解决您的问题。

相关问题