X-Original-To: pgsql-sql@postgresql.org Received: from spampd.localdomain (postgresql.org [64.49.215.8]) by postgresql.org (Postfix) with ESMTP id 716A6474E4F for ; Sat, 22 Mar 2003 04:52:16 -0500 (EST) Received: from news.hub.org (news.hub.org [64.49.215.80]) by postgresql.org (Postfix) with ESMTP id 36B0A474E44 for ; Sat, 22 Mar 2003 04:52:16 -0500 (EST) Received: by news.hub.org (Postfix, from userid 8) id 10AC043A670; Sat, 22 Mar 2003 04:52:15 -0500 (EST) From: Harald Fuchs X-Newsgroups: comp.databases.postgresql.sql Subject: Re: Diffcult query Date: 22 Mar 2003 10:52:19 +0100 Organization: Linux Private Site Lines: 38 Message-ID: References: Reply-To: hf303@protecting.net Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii X-Complaints-To: usenet@news.hub.org X-No-Archive: yes User-Agent: Gnus/5.0808 (Gnus v5.8.8) Emacs/20.7 To: pgsql-sql@postgresql.org X-Spam-Status: No, hits=-16.1 required=5.0 tests=QUOTED_EMAIL_TEXT,REFERENCES,USER_AGENT_GNUS_UA autolearn=ham version=2.50-cvs X-Spam-Level: X-Spam-Checker-Version: SpamAssassin 2.50-cvs (1.172-2003-02-14-exp) X-Archive-Number: 200303/531 X-Sequence-Number: 12570 In article , "Dan Winslow" 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;