简体   繁体   中英

Calculation (adding) in SQL

Values from different columns are required to be added with 10 marks each if there value is 1.
The accumulated result is required to be summed up in a column of a table. However, the sum should not exceed 20 marks. Thus, if the sum comes to 30, the result in column would always be 20.

SELECT 
    CASE 
        WHEN paint.is_weak  = 1 
            THEN 10 
        ELSE 0
    END
        +
    CASE
        WHEN paint.is_low  = 1 
            THEN 10 
        ELSE 0
    END
        +
    CASE
        WHEN paint.is_hi = 'red'
            THEN 10 
        ELSE 0
    END
from PAINT;

How will i ensure that the sum should not exceed 20 and is there any possibility of having a variable defined in SQL.

select least(((is_weak = 1) + (is_low = 1) + (is_hi = 1)) * 10, 20)
from paint

And BTW yes, you can have variables in MySQL. You can define one directly in a query with a subquery like this

select t.*, @your_var := @your_var + 1
from your_table t
cross join (select @your_var := 0) v

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM