Search code examples
sqlsumaggregate

How to sum quantity in sql


I have a simple table with these columns:

Id, quantity, deleted

Deleted is nullable.

I want to get sum of quantity of all rows,sum of quantity of rows that deleted is null, sum of quantity of rows that deleted is not null in one query.

How can I do that?


Solution

  • You could sum over a couple of case expressions:

    SELECT SUM(CASE WHEN deleted IS NULL THEN quantity END) AS sum_deleted_is_null,
           SUM(CASE WHEN deleted IS NOT NULL THEN quantity END) AS sum_deleted_is_not_null
    FROM   mytable