Re: Selecting rows as if they were columns?

From: Harald Fuchs <nospam(at)sap(dot)com>
To: pgsql-sql(at)postgresql(dot)org
Subject: Re: Selecting rows as if they were columns?
Date: 2003-10-09 13:40:03
Message-ID: pun0cattqk.fsf@srv.protecting.net
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

In article <3F855F38(dot)9070803(at)hotdogrecords(dot)com>,
Kurt Overberg <kurt(at)hotdogrecords(dot)com> writes:

> Gang,
> I've got what I think should be a pretty simple problem- I just can't
> figure out how I'd do it. Heck, I can't even figure out how I'd
> search for an answer to this problem.

> I've got 2 tables: member and member_attr

> Member is just a standard entry for a member. Very simple:

> table member {
> id integer,
> name character varying(30)
> }

> Member_attr is just a table of name/value pairs, such as:

> table memberextra {
> memberid integer,
> param1 character varying(512),
> param2 character varying(512),
> }

> where param1 is the name, param2 is the value.

> Right now, I can:

> select member.id, member.name, member_attr.param1, member_attr.param2
> from member, member_attr where member.id = member_attr.memberid;

> ...this gives me n rows per member where n = # of attributes for that
> member, like this:

> id | name | param1 | param2
> =======================================
> 1 | dave | home | /home/dave
> 1 | dave | testing | 1
> 2 | john | home | /home/john

> ...is there some way to make this return like this:

> id | name | home | testing
> ======================================
> 1 | dave | /home/dave | 1
> 2 | john | /home/john |

> ...where it sort of "expands" the rows out into columns? Am I just
> going about this the wrong way? Thoughts on the subject would be
> greatly appreciated.

This should work fine as long as you know all possible values of
param1 in advance:

SELECT m.id, m.name, m1.param2, m2.param2
FROM member m
LEFT JOIN memberextra m1 ON m1.memberid = m.id AND m1.param1 = 'home'
LEFT JOIN memberextra m2 ON m2.memberid = m.id AND m2.param1 = 'testing'

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Jan Wieck 2003-10-09 13:45:30 Re:
Previous Message Kurt Overberg 2003-10-09 13:14:32 Selecting rows as if they were columns?