Re: PIVOT of data

From: "Oliver Elphick" <olly(at)lfix(dot)co(dot)uk>
To: Srikanth Rao <srirao_us(at)yahoo(dot)com>
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: PIVOT of data
Date: 2001-03-14 23:03:01
Message-ID: 200103142303.f2EN31G25419@linda.lfix.co.uk
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

Srikanth Rao wrote:
>Hi,
>I have a table like this:
> location | numbrochures | marketing
>-----------------------+--------------+-----------
> 101 Asheville, NC | 4 | NEWS
> 101 Asheville, NC | 1 | TV
> 101 Asheville, NC | 3 | RADIO
> 101 Asheville, NC | 2 | OTHER
> 101 Asheville, NC | 3 | null
> 101 Asheville, NC | 1 | TV
> 102 'Charlotte', 'NC' | 1 | SIGN
> 104 'Colfax', 'NC' | 5 | SIGN
> 109 'Moyock', 'NC' | 1 | BROCHURE
>(9 rows)
>
>
>I want the headings to be like:
>
>location | NEWS | TV | RADIO | OTHER | ........
>
>How to get this done using sql for postgresql backend?

SELECT location,
CASE WHEN marketing = 'NEWS'
THEN numbrochures
ELSE NULL
END AS "NEWS",
CASE WHEN marketing = 'TV'
THEN numbrochures
ELSE NULL
END AS "TV",
...

but it's a clumsy hack and won't work if you don't know the
contents of "marketing" in advance.

--
Oliver Elphick Oliver(dot)Elphick(at)lfix(dot)co(dot)uk
Isle of Wight http://www.lfix.co.uk/oliver
PGP: 1024R/32B8FAA1: 97 EA 1D 47 72 3F 28 47 6B 7E 39 CC 56 E4 C1 47
GPG: 1024D/3E1D0C1C: CA12 09E0 E8D5 8870 5839 932A 614D 4C34 3E1D 0C1C
========================================
"Let your light so shine before men, that they may see
your good works, and glorify your Father which is in
heaven." Matthew 5:16

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message datactrl 2001-03-15 01:14:20 Re: psql win32 version
Previous Message Ross J. Reedstrom 2001-03-14 23:01:43 Re: need to join successive log entries into one