Filter as count on SQL SERVER

54 Views Asked by At

Helo!

How I make the following syntax of postgresql in SQL server without create subquery

PGSQL:

SELECT 
    COUNT(*) AS "QUANTIDADE TOTAL",
    COUNT(*) FILTER(WHERE SEXO = 'Masculino') AS "MASCULINO"
FROM FUNCIONARIOS;

I tried but got an error:
Message 156, Level 15, State 1, Line 4

Incorrect syntax next to 'WHERE' keyword.

2

There are 2 best solutions below

1
Shah On BEST ANSWER

Try SELECT COUNT(x) as [Quantudate Total], SUM (CASE WHEN SEXO = 'Masculino' THEN 1 ELSE 0 END) AS MASCULINO FROM FUNCIONARIOS

For better performance always better to use one specific field in the aggregate function than using a , eg use COUNT(id) than COUNT()

3
Isolated On

Conditional aggregation would work...

SELECT 
    COUNT(*) AS "QUANTIDADE TOTAL",
    SUM(case when SEXO = 'Masculino' then 1 end) AS "MASCULINO"
FROM FUNCIONARIOS;