简体   繁体   中英

SELECT inside a COUNT

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

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM