需要带有存储过程的 SQLQuery 以及以下示例
Need SQLQuery with Stored procedure with below example
我有以下MySQL-table
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
如果您的 table 上的 Id
是唯一的,您可以这样做(您已经很接近了……只是您的查询中遗漏了 case when
):
select
Id,
(ifnull(one,0) + ifnull(two,0) + ifnull(three,0))/
(
(case when one is not null then 1 else 0 end) +
(case when two is not null then 1 else 0 end) +
(case when three is not null then 1 else 0 end)
) as average
from {your_table}
你可以测试这个db<>fiddle
我有以下MySQL-table
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
如果您的 table 上的 Id
是唯一的,您可以这样做(您已经很接近了……只是您的查询中遗漏了 case when
):
select
Id,
(ifnull(one,0) + ifnull(two,0) + ifnull(three,0))/
(
(case when one is not null then 1 else 0 end) +
(case when two is not null then 1 else 0 end) +
(case when three is not null then 1 else 0 end)
) as average
from {your_table}
你可以测试这个db<>fiddle