Re: Crosstab Problems

From: Stefan Schwarzer <stefan(dot)schwarzer(at)grid(dot)unep(dot)ch>
To: pgsql-general(at)postgresql(dot)org
Subject: Re: Crosstab Problems
Date: 2007-10-19 08:45:16
Message-ID: 73994295-1801-493D-B48C-5783FAA863DC@grid.unep.ch
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general pgsql-patches

>> But when re-doing the query now without the JOIN, it works (almost):
>>
>> SELECT
>> *
>> FROM
>> crosstab(
>> 'SELECT
>> id_country AS id,
>> year_start AS year,
>> value
>> FROM
>> agri_area AS d
>> WHERE
>> year_start = 2003 OR year_start = 2002 OR year_start =
>> 2001 ORDER BY year_start ASC, id_country ASC;'
>> , 3)
>> AS ct(id int2, y_2003 numeric, y_2002 numeric, y_2001 numeric)
>>
>> Now, the problem is that it lists three times the IDs, and only the
>> first year column is filled with values. The other two year columns
>> stay empty.
>
> You missed this point in the docs:
>
> Notes
>
> 1. The sql result must be ordered by 1,2.
> Change your order by to that and it works fine.

Oh, great. No, haven't seen it. Now it works. Thanks a lot!

Just for the completeness, I attach the SQL.

SELECT
*
FROM
crosstab(
'SELECT
COALESCE(c.name, ''''),
year_start AS year,
value
FROM
agri_area AS d
LEFT JOIN
countries AS c ON c.id = id_country
WHERE
year_start = 2003 OR year_start = 2002 OR year_start = 2001
GROUP BY
name, id_country, year_start, value
ORDER BY 1,2;'
, 3)
AS ct(name varchar, y_2003 numeric, y_2002 numeric, y_2001 numeric)

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Ciprian Dorin Craciun 2007-10-19 09:32:41 Stalled post to pgsql-bugs
Previous Message Albe Laurenz 2007-10-19 07:36:49 Re: relations does not exist

Browse pgsql-patches by date

  From Date Subject
Next Message Gregory Stark 2007-10-19 10:48:22 Re: Crosstab Problems
Previous Message Joe Conway 2007-10-19 04:09:33 Re: Crosstab Problems