Two WHERE & COUNT in one query

I need to get two summations in one query based on different criteria. Both criteria work in one column. Is there any way to do this?

I can best explain this with an example:

Table: salary_survey_result

Columns: industry, location, position, salary

In fact, I want to combine the following two queries:

SELECT industry, location, count(*) as MORE_THAN_SIX_FIGURE FROM salary_survey_result WHERE salary > 100000 GROUP BY industry, location 

and

 SELECT industry, location, count(*) as MORE_THAN_FIVE_FIGURE FROM salary_survey_result WHERE salary > 10000 GROUP BY industry, location 

So, the result looks something like this:
industry location MORE_THAN_FIVE_FIGURE MORE_THAN_SIX_FIGURE


 Healthcare NY 45 10 Healthcare MN 35 6 InfoTech NY 50 19 InfoTech MN 40 12 
+4
source share
2 answers

Sort of

 SELECT industry, location, sum( case when salary >= 10000 then 1 else 0 end) as MORE_THAN_FIVE_FIGURE, sum( case when salary >= 100000 then 1 else 0 end) as MORE_THAN_SIX_FIGURE FROM salary_survey_result WHERE salary >= 10000 GROUP BY industry, location 

The WHERE salary >= 10000 not required for results. This can improve productivity if there is a SALARY index, and most salary values ​​are less than 10,000. Note that I also assume that you had >= , not > , since 10,000 people have a five-digit salary.

+8
source
 SELECT industry, location, count(*) as MORE_THAN_FIVE_FIGURE ,sum(salary > 100000) as MORE_THAN_SIX_FIGURE FROM salary_survey_result WHERE salary > 10000 GROUP BY industry, location 
-2
source

Source: https://habr.com/ru/post/1391937/


All Articles