简体   繁体   English

MySQL条件选择其他聚合语句

[英]MySQL conditional select else aggregate statement

I have several columns for which I'm selecting an average AVG() , some of which are quite small. 我有几列要为其选择平均AVG() ,其中有些很小。 I want to aggregate anything less than 0.01 to the result of "other". 我想将小于0.01的任何内容汇总到“其他”的结果中。

Something like: 就像是:

SELECT 
  AVG(data_1) as data_1, 
  AVG(data_2) as data_2, 
  AVG(data_3) as data_3, 
  AVG(data_4) as data_4, 
  AVG(data_5) as data_5
FROM my_table AS my_results;
SET @other = 0;
IF my_results.data_1 > 0.01 THEN
 SET my_results.data_1 my_results.data_1
ELSE 
 @other := @other + my_results.data_1
 UNSET my_results.data_1
[... repeat for data_2 - data_5 ]
RETURN my_results

But that's as far as I've gotten. 但这是我所知道的。 I'd want any data not more then 0.01 to be removed from the results after being aggregated to @other . 我希望在聚合到@other之后从结果中删除不超过0.01的任何数据。 Even a good pointer in the right direction is greatly appreciated! 即使是正确方向的好指针,也将受到赞赏!

Thanks 谢谢

You can not change number of selected columns during the query, however, you can set values to null if avg < 0.01 Here an example (I'm sure, it could be written in better way) 您无法在查询期间更改选定列的数量,但是,如果avg <0.01,则可以将值设置为null这里是一个示例(我敢肯定,可以用更好的方式编写)

SELECT 
  if(AVG(d1) < 0.01, null, AVG(d1)) as data_1,
  if(AVG(d2) < 0.01, null, AVG(d2)) as data_2,
  if(AVG(d3) < 0.01, null, AVG(d3)) as data_3,
  if(AVG(d4) < 0.01, null, AVG(d4)) as data_4,
  if(AVG(d5) < 0.01, null, AVG(d5)) as data_5,
  if(AVG(d1) < 0.01, AVG(d1), 0) +
  if(AVG(d2) < 0.01, AVG(d2), 0) +
  if(AVG(d3) < 0.01, AVG(d3), 0) +
  if(AVG(d4) < 0.01, AVG(d4), 0) +
  if(AVG(d5) < 0.01, AVG(d5), 0)

FROM my_table AS my_results, (select @other := 0) o

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM