0

What is the most elegant/efficient way to check multiple different count()'s with different conditions within the same statement? Given the syntax of SQL, it appears that I can only have one count() statement with each set of WHERE/HAVING conditionals within my query. Therefore, to utilize a different set of WHERE/HAVING conditionals, it seems this second count(*) needs to be in a different select statement. Is the best way to put this into the same result set to UNION them? Is there any alternative?
Ideally I could do something like:

SELECT count(*) as First, count(*) as Second  
FROM table  
WHERE --conditionals for First  
AND  
--conditionals for Second  

But I think this is impossible. Is the only way to do it to UNION two separate queries?

3
  • What you want here is a case expression. SELECT COUNT(CASE WHEN //conditionals THEN 1 END), COUNT(CASE WHEN //conditionals THEN 1 END) as Second FROM table; Commented Aug 24, 2021 at 15:56
  • You would use conditional aggregation where COUNT is implemented as SUM(CASE WHEN ... 1 ELSE 0 END). Commented Aug 24, 2021 at 15:58
  • You can combine conditional aggregation (SUM+CASE) with window frames (OVER). Commented Aug 24, 2021 at 15:59

2 Answers 2

4

The canonical method uses case with an aggregation function:

select sum(case when condition1 then 1 else 0 end),
       sum(case when condition2 then 1 else 0 end)

The SQL Standard method uses filter:

select count(*) filter (where condition1),
       count(*) filter (where condition2)
Sign up to request clarification or add additional context in comments.

Comments

1

It might not be the most efficient but you could use sub-queries:

SELECT
    (SELECT Count (*) FROM table WHERE <conditionals for First> ) As First,
    (SELECT Count (*) FROM table WHERE <conditionals for Second>) As Second

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.