Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

filtering inside COUNT in sql server [duplicate]

Tags:

sql-server

Possible Duplicate:
SQL Equivalent of COUNTIF()

Can I incorporate some kind of filtering mechanism inside COUNT itself, which I dont want to use in WHERE or JOINs of the query (since it is a part of large query in which there are other columns too which I dont want to get affected by where and join conditions).

For example I can use case inside SUM

SUM(CASE WHEN work_status IN ('V','L') THEN shift_total_hours ELSE 0 END),

Can I do something like this in COUNT too, so that I would get count for particular rows only

something like this:

COUNT(CASE WHEN work_status IN ('V','L') THEN <should come in count> ELSE <exclude from count> END)

many thanks.

like image 886
Tintin Avatar asked Mar 25 '11 15:03

Tintin


2 Answers

You can just use

COUNT(CASE WHEN work_status IN ('V','L') THEN 1 END)

For rows not matching the specified condition the CASE expression returns NULL and COUNT only counts NOT NULL values

like image 55
Martin Smith Avatar answered Sep 22 '22 15:09

Martin Smith


This should do what you want:

SUM(CASE WHEN work_status IN ('V','L') THEN 1 ELSE 0 END)

Although it is using the SUM aggregate function, it is effectively a conditional count because for each row, you are adding either 1 or 0 to the sum.

like image 25
Greg Avatar answered Sep 20 '22 15:09

Greg