【问题标题】:SQL query using stored procedure使用存储过程的 SQL 查询
【发布时间】:2022-01-30 18:45:27
【问题描述】:

我在 MySQL 中有一个包含三列的表,需要使用存储过程平均每行的三列:

Id  |  One  |  Two  |  Three
----+-------+-------+-------
1   |  10   |  30   |  20
2   |  50   |  60   |  20
3   |  60   |  0    |  40

必须使用存储过程而不是普通查询来确定平均值。

我有这个 SQL 查询

select
    id, 
    (ifnull(one, 0) + ifnull(two, 0) + ifnull(three, 0)) /
        ((one is not null) + (two is not null) + (three is not null)) as average 
from table

我希望它看起来像这样,带有 MySQL 查询:

Id | Average
---+--------
1  | 20
2  | 43.3
3  | 50

【问题讨论】:

  • 为什么要删除答案?
  • @AaronBertrand 我是一名学生,我不了解基本知识。现在学习如果我错了对不起

标签: mysql sql stored-procedures


【解决方案1】:

也许不是最好的解决方案,但您可以使用:

select id, 
       SUM(coalesce(one,0)+coalesce(two,0)+coalesce(three,0)) /
       count(CASE WHEN one != 0 and one is not null  then 1 ELSE NULL END) 
       + count(CASE WHEN two != 0 and two is not null  then 1 ELSE NULL END) 
       + count(CASE WHEN three  != 0 and three is not null  then 1 ELSE NULL END )  as average 

from my_table
group by id;

结果:

id    average
1     20.0000
2     43.3333
3     50.0000
4     35.0000

Demo

此查询不包括 Null0

coalesce

完整程序

DELIMITER//
CREATE PROCEDURE average()
BEGIN 

    select id, SUM(coalesce(one,0)+coalesce(two,0)+coalesce(three,0)) /(count(CASE WHEN one != 0 and one is not null  then 1 ELSE NULL END) + count(CASE WHEN two != 0 and two is not null  then 1 ELSE NULL END) + count(CASE WHEN three  != 0 and three is not null  then 1 ELSE NULL END))  as average from my_table group by id ;

END
DELIMITER ;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-22
    • 1970-01-01
    • 1970-01-01
    • 2012-07-21
    • 2015-04-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多