Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server count case

I have table in SQL Server with values for example :

1
2
2
2
1
2

I want to count how many times there is 1 value, so result of query from my example should be 2

I try

count (case status_d when 1 then 1 end) as COUNT_STATUS_1 

but the result is 4, not 2

like image 743
user1762186 Avatar asked Aug 24 '14 16:08

user1762186


People also ask

Can you use case in COUNT SQL?

The function counta can be implemented with a case expression as well. For that, SQL makes a distinction between empty strings and the null value. The following expression counts the rows that have neither the null value or the empty string.

How do I COUNT a condition in SQL?

COUNT() with HAVINGThe HAVING clause with SQL COUNT() function can be used to set a condition with the select statement. The HAVING clause is used instead of WHERE clause with SQL COUNT() function.

How do I COUNT multiple conditions in SQL?

You can count multiple COUNT() for multiple conditions in a single query using GROUP BY. SELECT yourColumnName,COUNT(*) from yourTableName group by yourColumnName; To understand the above syntax, let us first create a table. The query to create a table is as follows.

How does COUNT (*) work in SQL?

COUNT(*) returns the number of rows in a specified table, and it preserves duplicate rows. It counts each row separately. This includes rows that contain null values.


1 Answers

You can achieve this by using a WHERE clause.

SELECT COUNT(*) As Total_Ones
FROM TABLE_NAME
WHERE ColumnName = 1

Or you can use the case statement as well

SELECT COUNT(CASE WHEN ColumnName = 1 THEN 1 ELSE NULL END) As Total_Ones
FROM TABLE_NAME
like image 89
M.Ali Avatar answered Oct 13 '22 21:10

M.Ali