Received: from localhost (unknown [200.46.208.211]) by mail.postgresql.org (Postfix) with ESMTP id E14BD63355E for ; Thu, 10 Dec 2009 13:00:49 -0400 (AST) Received: from mail.postgresql.org ([200.46.204.86]) by localhost (mx1.hub.org [200.46.208.211]) (amavisd-maia, port 10024) with ESMTP id 03677-08 for ; Thu, 10 Dec 2009 17:00:38 +0000 (UTC) X-Greylist: domain auto-whitelisted by SQLgrey-1.7.6 Received: from lo.gmane.org (lo.gmane.org [80.91.229.12]) by mail.postgresql.org (Postfix) with ESMTP id 2C3816326AC for ; Thu, 10 Dec 2009 13:00:39 -0400 (AST) Received: from list by lo.gmane.org with local (Exim 4.50) id 1NImNW-0005lX-DC for pgsql-sql@postgresql.org; Thu, 10 Dec 2009 18:00:34 +0100 Received: from srv.protecting.net ([212.126.218.242]) by main.gmane.org with esmtp (Gmexim 0.1 (Debian)) id 1AlnuQ-0007hv-00 for ; Thu, 10 Dec 2009 18:00:34 +0100 Received: from hari.fuchs by srv.protecting.net with local (Gmexim 0.1 (Debian)) id 1AlnuQ-0007hv-00 for ; Thu, 10 Dec 2009 18:00:34 +0100 X-Injected-Via-Gmane: http://gmane.org/ To: pgsql-sql@postgresql.org From: Harald Fuchs Subject: Window function trouble Date: Thu, 10 Dec 2009 18:00:08 +0100 Lines: 56 Message-ID: Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii X-Complaints-To: usenet@ger.gmane.org X-Gmane-NNTP-Posting-Host: srv.protecting.net X-Archive: encrypt User-Agent: Gnus/5.11 (Gnus v5.11) Emacs/22.2 (gnu/linux) Cancel-Lock: sha1:OACeY0CWdXgxi/TP71fYZOuqZEs= X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=-2.599 tagged_above=-10 required=5 tests=AWL=0.000, BAYES_00=-2.599 X-Spam-Level: X-Archive-Number: 200912/27 X-Sequence-Number: 33465 I have a table like this: CREATE TABLE tbl ( host text NOT NULL, adr ip4 NOT NULL, usr text NOT NULL ); (ip4 is from the ip4r contrib module) and I want the number of entries per address and per user: SELECT adr, usr, count(*) FROM tbl WHERE host = ? AND adr <<= ? GROUP BY adr, usr ORDER BY adr, usr That's pretty basic stuff and returns something like this: adr1 usr1_1 cnt1_1 adr1 usr1_2 cnt1_2 adr1 usr1_3 cnt1_3 adr2 usr2_1 cnt2_1 ... But I want the address to be NULL if it's the same as the address of the previous row. I came up with this: SELECT CASE lag(adr) OVER (ORDER BY adr) WHEN adr THEN NULL ELSE adr END AS myaddr, usr, count(*) FROM tbl WHERE host = ? AND adr <<= ? GROUP BY adr, usr ORDER BY adr, usr This returns something like adr1 usr1_1 cnt1_1 NULL usr1_2 cnt1_2 NULL usr1_3 cnt1_3 adr2 usr2_1 cnt2_1 ... what's exactly what I want. But when I don't name the CASE expression (i.e. I delete "AS myaddr"), I get the following: adr1 usr1_1 cnt1_1 adr2 usr2_1 cnt2_1 ... The other users for one address are gone. Does anyone know why?