[英]MySQL conditional select else aggregate statement
我有幾列要為其選擇平均AVG()
,其中有些很小。 我想將小於0.01的任何內容匯總到“其他”的結果中。
就像是:
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,則可以將值設置為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.