SQL - How to get the correct number

I wrote a personal pseudo code to help others understand what I'm trying to achieve. I am new to SQL, but I know all the basics, just not experienced enough with features.

I tried using SELECT CASE, but it does not achieve what I need.

Here is my sample data

CREATE TABLE Records
    ([ColA] INTEGER, [ColB] INTEGER, [ColTotal] INTEGER)
;

INSERT INTO Records
    ([ColA], [ColB] )
VALUES
    ('3', '4'),
    ('4', '2’),
    ('1', '2'),
    ('3', '5'),
    ('3', '1'),
    ('2', '2')
;

Here is my PSEUDOCODE (I found out after the accepted answer that my psuedo logic was wrong too. This has been fixed)

SELECT COL A, COL B, COL TOTAL
IF COL A  >= COLB THEN
ADD COLB value to COL TOTAL
ELSE
USE Value from COLA and add to total
END IF

Here is my SQL

SELECT SUM(ColTotal)
FROM t
WHERE ColA >= ColB
+4
source share
1 answer

Is this what you want?

select sum(case when a < b then a else b end) as total
from t;

Many databases support a feature least()that makes this easier:

select sum(least(a, b)) as total
from t;
+3
source

Source: https://habr.com/ru/post/1680572/


All Articles