Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
455 views
in Technique[技术] by (71.8m points)

mysql - Sum values of a single row?

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

Edit: 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

Correct?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...