Metta
Metta

Reputation: 13

SQL sum function with where clause

I am using MsSQL and I want to add some values where some conditions are met. Is it possible to use WHERE clause in the sum() function? Or is there an equivalent function to the excel SUMIF().

Upvotes: 1

Views: 5115

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460048

You could use CASE:

SELECT SUM(CASE WHEN YourCondition=1 THEN 1 ELSE 0 END)
FROM YourTable

Upvotes: 1

Oded
Oded

Reputation: 498914

The SUM aggregate will only operate on the result set constrained by the WHERE clause.

In other words, yes, this is fine.

SELECT SUM(days)
FROM myTable
WHERE something = another

Upvotes: 2

Related Questions