RE: [pgsql-es-ayuda] agrupar totales por años y por meses en una misma consulta

From: "Fernando Hevia" <fhevia(at)ip-tel(dot)com(dot)ar>
To: 'angel Nuñez Conde' <afiladostoledo(at)gmail(dot)com>, <pgsql-es-ayuda(at)postgresql(dot)org>
Subject: RE: [pgsql-es-ayuda] agrupar totales por años y por meses en una misma consulta
Date: 2009-09-01 18:21:18
Message-ID: 91A8AD877EB34A2CBC8D3EF333D752B4@iptel.com.ar
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-es-ayuda

> -----Mensaje original-----
> De: angel Nuñez Conde
>
> Hola a todos.
>
> Soy novato en postgresql, tengo una vista con los campos
> id int
> fecha date
> total numeric
>
> agrupo por meses mediante la consulta :
>
> select date_part('year',w.fecha) as año ,
> date_part('month'::text, w.fecha)as mes, sum(w.total) as total_mes
> from w_totalalbaran w where w.fecha between '25-08-1998'
> and '31-12-1999'
> group by date_part('year',w.fecha),
> date_part('month'::text, w.fecha) order by 1,2
>
> o por años:
>
> select date_part('year',w.fecha) as año , sum(w.total) as total_mes
> from w_totalalbaran w where w.fecha between '25-08-1998'
> and '31-12-1999'
> group by date_part('year',w.fecha)order by 1,2
>
> quiero una consulta que me de totales de meses y años, no se
> como hacerlo. He intentado una subconsulta pero no funciona me da
> ERROR: una subconsulta utilizada como expresión retornó más
> de un registro
>

No se si es lo que tienes en mente pero podría ser con:

SELECT date_part('year',w.fecha) as año, date_part('month'::text, w.fecha)
as mes, sum(w.total) as total_mes
FROM w_totalalbaran w
WHERE w.fecha between '25-08-1998' and '31-12-1999'
GROUP BY date_part('year',w.fecha), date_part('month'::text, w.fecha)

UNION

SELECT date_part('year',w.fecha) as año, 0 as mes, sum(w.total) as total_mes
FROM w_totalalbaran w where w.fecha between '25-08-1998' and '31-12-1999'

GROUP BY año, mes
ORDER BY 1,2

Si el mes tiene valor 0 entonces te está mostrando los acumulados para todo
el año.

Saludos,
Fernando.

In response to

Browse pgsql-es-ayuda by date

  From Date Subject
Next Message Diego Ayala 2009-09-01 18:31:13 Re: ayuda para implementar replicacion
Previous Message Diego Ayala 2009-09-01 18:18:37 ayuda para implementar replicacion