我有一个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;
2条答案
按热度按时间laximzn51#
似乎你想在子查询方面胜过mysql。至于关注点,您不需要这种额外的复杂性,只需使用一个简单的聚合查询,其中包含一个where子句,用于过滤具有mt=“qt”的记录。
b4qexyjb2#
我想你唯一的问题是
ELSE 0
. 你只是想NULL
值,因为它们将被忽略:请注意某些其他更改:
我简化了计数的逻辑,去掉了
CASE
表情。这使用了一个mysql扩展,它将布尔值视为带有1
为了真实和0
为假。我用单引号代替了双引号。单引号是字符串的标准分隔符。
我移除了
ELSE
条款。聚合函数忽略NULL
值,所以这应该可以解决您的问题。