Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TSQL Count 'Where' Condition

How do I implement the 'meaning' of the following psuedo-SQL statement:

COUNT(distinct id where attribute1 > 0)

In other words, how do I make conditional, distinct counting statements?

Thanks!

like image 951
CodeKingPlusPlus Avatar asked Jul 26 '12 18:07

CodeKingPlusPlus


People also ask

Can I use COUNT in WHERE clause?

SQL SELECT COUNT() can be clubbed with SQL WHERE clause.

How do you COUNT by condition in SQL?

For this, you can write a SELECT query with COUNT(*) and a WHERE clause. However, You can have the same result by using a condition inside CASE() function. If you see the second SQL statement below, I have added a CASE statement with condition inside the COUNT().

What does COUNT (*) do in SQL?

COUNT(*) returns the number of items in a group. This includes NULL values and duplicates. COUNT(ALL expression) evaluates expression for each row in a group, and returns the number of nonnull values.

How do I COUNT multiple values 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.


1 Answers

Well, if you can filter the entire query, then LittleBobbyTables already has the answer for you. If not, you can get that column like so:

count(distinct case when attribute1 > 0 then id end) -- implicit null-else, iirc
like image 90
canon Avatar answered Oct 03 '22 10:10

canon