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.
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.
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.
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.
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
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