Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using sql count in a case statement

Tags:

sql

I have a table and i need to present the output in the following fashion.

tb_a:  col1  |  reg_id | rsp_ind  

Count of rows with rsp_ind = 0 as 'New' and 1 as 'Accepted'

The output should be

NEW | Accepted 9   | 10 

I tried using the following query.

select    case when rsp_ind = 0 then count(reg_id)end as 'New',   case when rsp_ind = 1 then count(reg_id)end as 'Accepted' from tb_a 

and i m getting output as

NEW | Accepted NULL| 10 9   | NULL 

Could someone help to me tweak the query to achieve the output. Note : I cannot add a sum surrounding this. Its part of a bigger program and so i cannot add a super-query to this.

like image 751
Raghav Avatar asked Jul 31 '13 15:07

Raghav


People also ask

Can I use count in case statement in SQL?

CASE can be used in conjunction with SUM to return a count of only those items matching a pre-defined condition. (This is similar to COUNTIF in Excel.) The trick is to return binary results indicating matches, so the "1"s returned for matching entries can be summed for a count of the total number of matches.

How do I count rows in SQL with conditions?

The SQL COUNT() function returns the number of rows in a table satisfying the criteria specified in the WHERE clause. It sets the number of rows or non NULL column values. COUNT() returns 0 if there were no matching rows.

Can we use aggregate function in case statement?

CASE statement in SQL and aggregate functions Aggregate functions in SQL Server perform calculations and return a single value. Examples of aggregate functions are MIN, MAX, COUNT, ABG and CHECKSUM. For this purpose, we use the COUNT aggregate function in SQL Server.


1 Answers

SELECT      COUNT(CASE WHEN rsp_ind = 0 then 1 ELSE NULL END) as "New",     COUNT(CASE WHEN rsp_ind = 1 then 1 ELSE NULL END) as "Accepted" from tb_a 

You can see the output for this request HERE

like image 100
B F Avatar answered Sep 19 '22 15:09

B F