Re: query like this???
От | Michael Fuhr |
---|---|
Тема | Re: query like this??? |
Дата | |
Msg-id | 20050427164340.GA88491@winnie.fuhr.org обсуждение исходный текст |
Ответ на | query like this??? (Akbar <tuxer@myrealbox.com>) |
Ответы |
Re: query like this???
|
Список | pgsql-novice |
On Wed, Apr 27, 2005 at 11:12:48PM +0700, Akbar wrote: > > I want to ask what query will give me this output: > month sum > ----- --- > 2 0 > 3 0 > 4 9 > 5 6 > 6 0 > 7 6 > 8 0 > > but with this condition: > WHERE extract (month FROM datestock::timestamp) BETWEEN 2 AND 8 Here's one way: SELECT g.month, coalesce(sum(s.dummy), 0) AS sum FROM generate_series(2, 8) AS g(month) LEFT OUTER JOIN stupid AS s ON extract(month FROM s.datestock) = g.month GROUP BY g.month ORDER by g.month; The generate_series() function comes with PostgreSQL 8.0 and later, but it's easily written in earlier versions. Here's a simple example: CREATE FUNCTION generate_series(integer, integer) RETURNS SETOF integer AS ' DECLARE i integer; BEGIN FOR i IN $1 .. $2 LOOP RETURN NEXT i; END LOOP; RETURN; END; ' LANGUAGE plpgsql VOLATILE STRICT; -- Michael Fuhr http://www.fuhr.org/~mfuhr/
В списке pgsql-novice по дате отправления: