tags:

views:

97

answers:

4

I would like to embed a SELECT inside a COUNT, but I can't find any examples.

#pseudosql
SELECT a AS current_a, COUNT(*) AS b,
   COUNT( SELECT FROM t WHERE a = current_a AND c = 'const' ) as d,
   from t group by a order by b desc
+2  A: 

You can move the count() inside your sub-select:

SELECT a AS current_a, COUNT(*) AS b,
   ( SELECT COUNT(*) FROM t WHERE a = current_a AND c = 'const' ) as d,
   from t group by a order by b desc
Ike Walker
A: 

Use SELECT COUNT(*) FROM t WHERE a = current_a AND c = 'const' ) as d.

Femaref
A: 
SELECT a AS current_a, COUNT(*) AS b,
   (SELECT COUNT(*) FROM t WHERE a = current_a AND c = 'const' ) as d
   from t group by a order by b desc
Jeroen
+5  A: 

You don't really need a sub-select:

SELECT a, COUNT(*) AS b,
   SUM( CASE WHEN c = 'const' THEN 1 ELSE 0 END ) as d,
   from t group by a order by b desc
Justin K
+1 This addresses the OP's specific query in a more efficient way. I would use `IF()` instead of `CASE` since there are only 2 states, but removing the sub-query is the right thing to do.
Ike Walker