Sum values of a single row?

后端 未结 2 461
执笔经年
执笔经年 2020-12-02 20:57

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 th

相关标签:
2条回答
  • 2020-12-02 21:15

    You can't really do it any simpler than:

    SELECT item_1 + item_2 + item_3 + item_4
    FROM Table1
    

    If you have a lot of columns then it will take a while to type in. I guess it took quite a long time to create the table too.

    In future design your tables differently so that each stage of the process is a row not a column. In other words, instead of this:

    id, item_1, item_2, item_3, item_4
    

    Your table could look like this:

    id, item_number, value
    

    And then you can query it like this:

    SELECT SUM(value)
    FROM Table1
    WHERE id = @id
    

    In fact, you probably don't even need the value column. The presence or absence of the row is enough information. So your query becomes:

    SELECT COUNT(*)
    FROM Table1
    WHERE id = @id
    

    It's perhaps a bit late for you this time, but if you still have a chance to change the design, then it might be worth considering this.

    0 讨论(0)
  • 2020-12-02 21:36
    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
    
    0 讨论(0)
提交回复
热议问题