tengo la siguiente tabla
id | created_on | is_a | is_b | is_c ---------------------------------------------- 1 | 01-02-1999 | True |False |False 2 | 23-05-1999 | False |True |False 3 | 25-08-2000 | False |True |False 4 | 30-07-2000 | False |False |True 5 | 05-09-2001 | False |False |True 6 | 05-09-2001 | False |True |False 7 | 05-09-2001 | True |False |False 8 | 05-09-2001 | True |False |False En la tabla resultante de la consulta, me gustaría agrupar por año de creación y luego poder comparar cuántos registros se crearon en cada año para is_a e is_b . Quiero ignorar por completo del recuento is_c .
count_a | count_b | by_creation_year ----------------------------------------------- 1 |1 | 1999 0 |1 | 2000 2 |1 | 2001Intenté la siguiente consulta:
select count(is_a = True) a, count(is_b = True) b, date_trunc('year', created_on) from cp_all where is_c = False -- this removes the records where is_c is True group by date_trunc('year', created_on) order by date_trunc('year', created_on) asc;Pero obtengo una tabla donde el conteo de a y b es exactamente el mismo.
Su argumento count() se evalúa como true o false , cada uno de los cuales se cuenta como 1 independientemente.
Quieres usar filter
select count(*) filter (where is_a) a, count(*) filter (where is_b) b, date_trunc('year', created_on) from cp_all where is_c = False -- this removes the records where is_c is True group by date_trunc('year', created_on) order by date_trunc('year', created_on) asc; Si lo hace de esta manera, no necesitará la cláusula where .
Esto se debe a que count no toma expresiones booleanas, simplemente usa la expresión y evalúa para verificar si es null o not null para agregar al contador. Así que en este caso deberías usar sum con case
select sum(case when is_a then 1 else 0 end) a, sum(case when is_b then 1 else 0 end) b, date_trunc('year', created_on) from cp_all where is_c = False -- this removes the records where is_c is True group by date_trunc('year', created_on) order by date_trunc('year', created_on) asc;Aunque me gusta el filtro, esto es más fácil de escribir:
select sum(is_a::int) as a, sum(is_b::int) as b, date_trunc('year', created_on) from cp_all where is_c = False -- this removes the records where is_c is True group by date_trunc('year', created_on) order by date_trunc('year', created_on) asc;