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)?
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.
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.
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).
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With