37

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
  • 47
  • 78
Issac Kelly
  • 6,309
  • 6
  • 43
  • 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

48

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,664
  • 1
  • 19
  • 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
31

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
  • 64,401
  • 14
  • 110
  • 109
1

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

Femaref
  • 60,705
  • 7
  • 138
  • 176
-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
  • 24
  • 40