32

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
Braiam
  • 1
  • 11
  • 50
  • 74
Issac Kelly
  • 6,129
  • 6
  • 41
  • 50
  • 1
    Does this answer your question? [How to get multiple counts with one SQL query?](https://stackoverflow.com/questions/12789396/how-to-get-multiple-counts-with-one-sql-query) – Braiam Apr 17 '22 at 10:27

4 Answers4

45

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
  • 2,564
  • 1
  • 17
  • 16
  • 4
    +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 Jul 16 '10 at 17:23
28

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
  • 62,183
  • 14
  • 104
  • 106
1

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

Femaref
  • 59,667
  • 7
  • 131
  • 173
-1
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
  • 4,023
  • 2
  • 22
  • 40