Search Postgresql Archives

Re: Find min year and min value

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 




On Oct 2, 2007, at 9:29 , Stefan Schwarzer wrote:

How would I do that? I really have no clue...

The key is to build it up in steps.

select id_country, year, var_1, val_1, var_2, val_2
-- Second step:
-- value for year for each country of var_1
from (select id_country, year, id_variable as var_1, "value" as val_1
        from my_table) as val_1
-- value for year for each country for var_2
natural join (select id_country, year, id_variable as var_2, "value" as val_2
                from my_table) as val_2
-- First step
-- for each country, find the minimum common year (which the join will do) for the two
-- variables you're interested in (var_1 and var_2).
natural join (select id_country, var_1, var_2, min(year) as year
                from (select id_country, year, id_variable as var_1
                        from my_table) as var_1
natural join (select id_country, year, id_variable as var_2
                                from my_table) as var_2
                group by id_country, var_1, var_2) as min_common_year
where id_country = :id_country
  and var_1 = :var_1
  and var_2 = :var_2;

Check your explain analyze output: if the planner doesn't push up the :var_1, :var_2, and :id_country_id values up into subqueries, you might want to add them as where clauses.

As an aside, I assume you've rewritten the table column names: if you haven't, as it's an SQL keyword, "value" is a particularly poor choice of column name. I'd probably rename "year" as well.

Hope this helps.

Michael Glaesemann
grzm seespotcode net



---------------------------(end of broadcast)---------------------------
TIP 4: Have you searched our list archives?

              http://archives.postgresql.org/

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
[Index of Archives]     [Postgresql Jobs]     [Postgresql Admin]     [Postgresql Performance]     [Linux Clusters]     [PHP Home]     [PHP on Windows]     [Kernel Newbies]     [PHP Classes]     [PHP Books]     [PHP Databases]     [Postgresql & PHP]     [Yosemite]
  Powered by Linux