SQL: Count() based on column value

You can use a CASE expression with your aggregate to get a total based on the outcomeId value:

select companyId,
  sum(case when outcomeid = 36 then 1 else 0 end) SalesCount,
  sum(case when outcomeid <> 36 then 1 else 0 end) NonSalesCount
from yourtable
group by companyId;

See SQL Fiddle with Demo


Something like this:

SELECT companyId,
  COUNT(CASE WHEN outcomeid = 36 THEN 1 END) SalesCount,
  COUNT(CASE WHEN outcomeid <> 36 THEN 1 END) NonSalesCount
FROM 
  yourtable
GROUP BY 
  companyId

should work -- COUNT() counts only not null values.


Yes. Count doesn't count NULL values, so you can do this:

select
  COUNT('x') as Everything,
  COUNT(case when OutcomeID = 36 then 'x' else NULL end) as Sales,
  COUNT(case when OutcomeID <> 36 then 'x' else NULL end) as Other
from
  YourTable

Alternatively, you can use SUM, like bluefeet demonstrated.

Tags:

Sql

Count