MySQL 条件 select else 聚合语句
MySQL conditional select else aggregate statement
我选择了几个列的平均值 AVG()
,其中一些非常小。我想将小于 0.01 的任何值聚合到 "other" 的结果。
类似于:
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
但这就是我所得到的。我希望在聚合到 @other
后从结果中删除不超过 0.01 的任何数据。即使是正确方向的好指针也非常感谢!
谢谢
您不能在查询期间更改所选列的数量,但是,如果 avg < 0.01,您可以将值设置为空
这是一个例子(我敢肯定,它可以用更好的方式编写)
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
我选择了几个列的平均值 AVG()
,其中一些非常小。我想将小于 0.01 的任何值聚合到 "other" 的结果。
类似于:
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
但这就是我所得到的。我希望在聚合到 @other
后从结果中删除不超过 0.01 的任何数据。即使是正确方向的好指针也非常感谢!
谢谢
您不能在查询期间更改所选列的数量,但是,如果 avg < 0.01,您可以将值设置为空 这是一个例子(我敢肯定,它可以用更好的方式编写)
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