单行的总和值? [英] Sum values of a single row?
问题描述
我有一个MySQL查询,该查询返回由1和0组成的单行.用于进度条指示器.我现在已在代码中对其求和,但是我尝试对查询中的值求和,并意识到我不能使用SUM(),因为它们有很多列,但只有一行.
I have a MySQL query that returns a single row that is a series of 1s and 0s. It's for a progress bar indicator. I have the summing of it in code now, but I tried to sum the values in a query, and realized I couldn't use SUM(), because they're many columns but just one row.
有没有一种方法可以自动在查询中求和?就像这样:
Is there a way I can sum this automatically in the query? It's like this:
item_1 | item_2 | item_3 | item_4
-------+--------+--------+--------
1 | 1 | 0 | 0
我忘了提及,item_1
等不是简单的字段值,但是每个值都是一个表达式,例如SELECT IF( field_1 = 1 and field_2 IS NOT NULL, 0, 1 ) AS item_1 ...
,所以看起来我必须做一个嵌套查询:
I forgot to mention, item_1
and so forth are not simple field values, but each is rather an expression, such as SELECT IF( field_1 = 1 and field_2 IS NOT NULL, 0, 1 ) AS item_1 ...
, so it looks like I have to do a nested query:
SELECT ( item_1 + item_2 ... ) FROM ( SELECT IF( field_1 = y and field_2 IS NOT NULL, 1, 0 ) AS item_1 ... ) AS alias
正确吗?
推荐答案
select item_1 + item_2 + item_3 + item_4 as ItemSum
from MyTable
如果可以有空值,则需要按以下方式处理它们:
If there can be null values, you'll need to handle them like this:
select ifnull(item_1, 0) + ifnull(item_2, 0) + ifnull(item_3, 0) + ifnull(item_4, 0) as ItemSum
from MyTable
这篇关于单行的总和值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!