Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: Count() based on column value

Tags:

sql

count

I have a table as follows:

CallID   | CompanyID  | OutcomeID ---------------------------------- 1234     | 3344       | 36 1235     | 3344       | 36 1236     | 3344       | 36 1237     | 3344       | 37 1238     | 3344       | 39 1239     | 6677       | 37 1240     | 6677       | 37 

I would like to create a SQL script that counts the number of Sales outcomes and the number of all the other attempts (anything <> 36), something like:

CompanyID  | SalesCount  | NonSalesCount ------------------------------------------ 3344       | 3           | 1 6677       | 0           | 2 

Is there a way to do a COUNT() that contains a condition like COUNT(CallID WHERE OutcomeID = 36)?

like image 524
BrianKE Avatar asked Jun 19 '13 14:06

BrianKE


People also ask

How do I count a column value in SQL?

To count the number of different values that are stored in a given column, you simply need to designate the column you pass in to the COUNT function as DISTINCT . When given a column, COUNT returns the number of values in that column. Combining this with DISTINCT returns only the number of unique (and non-NULL) values.

How do you count by condition in SQL?

SQL COUNT() with HAVING The HAVING clause is used instead of WHERE clause with SQL COUNT() function. The GROUP BY with HAVING clause retrieves the result for a specific group of a column, which matches the condition specified in the HAVING clause.

How do I count the number of rows in SQL based on one column?

Use the COUNT aggregate function to count the number of rows in a table. This function takes the name of the column as its argument (e.g., id ) and returns the number of rows for this particular column in the table (e.g., 5).

How do I select a column and a count in SQL?

Here is the basic syntax: SELECT COUNT(column_name) FROM table_name; The SELECT statement in SQL tells the computer to get data from the table. COUNT(column_name) will not include NULL values as part of the count.


1 Answers

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

like image 182
Taryn Avatar answered Sep 30 '22 09:09

Taryn