Is it possible to specify a condition in Count()
? I would like to count only the rows that have, for example, "Manager" in the Position column.
I want to do it in the count statement, not using WHERE
; I'm asking about it because I need to count both Managers and Other in the same SELECT
(something like Count(Position = Manager), Count(Position = Other))
so WHERE
is no use for me in this example.
I think you can use a simple WHERE clause to select only the count some record.
@Guffa 's answer is excellent, just point out that maybe is cleaner with an IF statement
You can also use the Pivot Keyword if you are using SQL 2005 or above
more info and from Technet
Test Data Set
I know this is really old, but I like the
NULLIF
trick for such scenarios, and I found no downsides so far. Just see my copy&pasteable example, which is not very practical though, but demonstrates how to use it.NULLIF
might give you a small negative impact on performance, but I guess it should still be faster than subqueries.Comments appreciated :-)
Do you mean just this:
If so, then yup that works!