Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select sum(a), sum(b where c=1) from db; sql conditions in select statement

Tags:

sql

select

i guess i just lack the keywords to search, but this is burning on my mind:

how can i add a condition to the sum-function in the select-statement like

select sum(a), sum(b where c=1) from db;?

this means, i want to see the sum of column a and the sum of column b, but only of the records in column b of which column c has the value 1.

the output of heidi just says "bad syntac near WHERE". may there be any other way?

thanks in advance and best regards from Berlin, joachim

like image 840
josewe Avatar asked Jan 29 '26 20:01

josewe


2 Answers

The exact syntax may differ depending on the database engine, however it will be along the lines of

SELECT
    sum(a),
    sum(CASE WHEN c = 1 THEN b ELSE 0 END)
FROM
    db
like image 130
Aleks G Avatar answered Jan 31 '26 15:01

Aleks G


select sum(case when c=1 then b else 0 end)

This technique is useful when you need a lot of aggregates on the same set of data - you can query the entire table without applying a where filter, and have a bunch of these which give you aggregated data for a specific filter.

It's also useful when you need a lot of counts based on filters - you can do sums of 1 or 0:

select sum(case when {somecondition} then 1 else 0 end)
like image 28
Joe Enos Avatar answered Jan 31 '26 17:01

Joe Enos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!