Re: Diffcult query

From: Harald Fuchs <nospam(at)sap(dot)com>
To: pgsql-sql(at)postgresql(dot)org
Subject: Re: Diffcult query
Date: 2003-03-22 09:52:19
Message-ID: pusmtfohik.fsf@srv.protecting.net
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

In article <d9Iea(dot)117330$JE5(dot)48428(at)news2(dot)central(dot)cox(dot)net>,
"Dan Winslow" <d(dot)winslow(at)cox(dot)net> writes:

> Hi folks. This is giving me fits. I feel like it oughta be simple, but
> apparantly its not...I think.

> Given a table :

> create table tablea (
> code1 varchar(32),
> code2 varchar(32),
> cost int
> );

> and the rows

> code1 code2 cost
> ----------------------------------
> "aaa" "bbb" 2
> "ddd" "eee" 3
> "bbb" "aaa" 6
> "ggg" "hhh" 4

> I need a ( preferably single ) query that will sum the costs for all unique
> pairs of codes, without regard to column order. That is, for summing
> purposes, rows 1 and 3 are identical, and should produce the sum of 8 for
> the unordered pair("aaa","bbb"). It should also, of course, prevent the case
> where ("bbb","aaa") is considered a seperate pair. Any ideas would be much
> appreciated.

How about this one?

SELECT CASE WHEN code1 < code2 THEN code1 ELSE code2 END ||
'\0' ||
CASE WHEN code1 < code2 THEN code2 ELSE code1 END AS codes,
SUM(cost) AS costs
FROM tablea
GROUP BY codes;

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Rajesh Kumar Mallah 2003-03-22 10:03:44 Re: newline character in SQL
Previous Message Popeanga Marian 2003-03-22 09:08:42 Re: SQL help for efficient time handling..