HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlModerate

Count with where clause

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
withcountwhereclause

Problem

Is there a way to have WHERE clause in COUNT ? Or how to count with some clause ?

select 
  a
  b,
  count(c where t1.u='UAE') as c1 
from t1


I am using MS SQL Server 2014

Solution

No, the syntax you have is not valid, it can be corrected by the use of a CASE expression.

(and I guess you have a GROUP BY a, b as you'd get an error otherwise).

select 
  a
  b,
  count(case when t1.u = 'UAE' then c else null end) as c1 
from t1 
group by a, b ;


Note that the ELSE NULL is redundant and can be removed as that is the default ELSE behaviour anyway:

select 
  a
  b,
  count(case when t1.u = 'UAE' then c end) as c1 
from t1 
group by a, b ;


There is a (SQL Standard) FILTER syntax that is close to your attempt but SQL Server has not yet implemented it:

select 
  a
  b,
  count(c) filter (where t1.u = 'UAE') as c1 
from t1 
group by a, b ;

Code Snippets

select 
  a
  b,
  count(case when t1.u = 'UAE' then c else null end) as c1 
from t1 
group by a, b ;
select 
  a
  b,
  count(case when t1.u = 'UAE' then c end) as c1 
from t1 
group by a, b ;
select 
  a
  b,
  count(c) filter (where t1.u = 'UAE') as c1 
from t1 
group by a, b ;

Context

StackExchange Database Administrators Q#159346, answer score: 11

Revisions (0)

No revisions yet.