Calculation of different amounts depending on the value of one column

In psuedo code, this is basically what I would like to do:

select
    if a1 >= 0 and a1 <= 2
        a2 + a7 + a8 as sum
    else
        a2 + a8 as sum
from table_name
;

(Column names, etc. are for illustration only.)

In English: I need to summarize different columns for each of several thousand records. I would like to make a sum in SQL, if possible. There is only one or two differences between conditions: either one column is missing / added, or a replacement, or both. This is based on the business logic of the application, not the design decision of my choice.

I use sqlite3 (3.6.10), which somewhat restricts the options.

+5
source share
1 answer

, 0, 1 SQL:

SELECT a2 + a8 + a7 * (a1 BETWEEN 0 AND 2) AS SUM
FROM table_name

( ) CASE:

SELECT
    CASE WHEN a1 BETWEEN 0 AND 2
         THEN a2 + a7 + a8
         ELSE a2 + a8
    END AS SUM
FROM table_name

- , CASE :

SELECT
    a2 + a8 + (CASE WHEN a1 BETWEEN 0 AND 2 THEN a7 ELSE 0 END) AS SUM
FROM table_name
+8

All Articles