From: | "Victor Yegorov" <viy(at)pirmabanka(dot)lv> |
---|---|
To: | "Dan Winslow" <danwinslow(at)cox(dot)net> |
Cc: | pgsql-sql(at)postgresql(dot)org |
Subject: | Re: Seeking help with a query.... |
Date: | 2003-03-24 08:20:14 |
Message-ID: | 20030324082014.GG20481@pirmabanka.lv |
Views: | Raw Message | Whole Thread | Download mbox | Resend email |
Thread: | |
Lists: | pgsql-sql |
* Dan Winslow <danwinslow(at)cox(dot)net> [21.03.2003 21:58]:
> Hi folks, seeking help with a query that I thought was simple, but
> apparantly isn't, at least for someone with my knowledge level.
>
> Given a table :
>
> create table atable (
> code1 char,
> code2 char,
> cost int
> );
>
> And the rows
>
> code1 code2 cost
> -----------------------------
> a b 2
> d e 4
> b a 6
> f g 1
>
> I need a ( preferably single ) query that will sum the costs for any
> matching pairs of codes regardless of order. That is, row 1 and row 3
> concern the same pair of unordered codes (a,b), and the result should show
> that the (a,b) pair had a summed cost of 8. I am not able to change any of
> the environment or preconditions other than the query itself. I have tried
> so many approaches that they aren't even worth listing. Any suggestions
> would be very much appreciated.
First thing, that came to my mind:
Give each code (if they are not numeric) a number. For this example, that
could be ASCII code of chars. Create view on that table:
CREATE VIEW aview AS
SELECT at.*, code(at.code1) + code(at.code2) AS dbl_code FROM atable at;
dbl_code field will have equal values for all groups of codes with same
codes involved: a and b, b and a.
About function code() I used to create the View: it's just an assumption,
you should write one yourself (on C for faster perfomance). Or simply use:
code1 + code
if your codes are of numeric type and are foreign keys to some other table's
primary key.
Please, give some feedback on usability of this solution.
--
Victor Yegorov
From | Date | Subject | |
---|---|---|---|
Next Message | Tomasz Myrta | 2003-03-24 09:33:25 | Re: column label |
Previous Message | CN | 2003-03-24 08:17:14 | Which Approach Performs Better? |