Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA384:256) (Exim 4.89) (envelope-from ) id 1eu1X2-000180-9V for pgsql-sql@arkaria.postgresql.org; Thu, 08 Mar 2018 19:48:52 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.89) (envelope-from ) id 1eu1X0-0003M9-QN for pgsql-sql@arkaria.postgresql.org; Thu, 08 Mar 2018 19:48:50 +0000 Received: from makus.postgresql.org ([2001:4800:1501:1::229]) by malur.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA384:256) (Exim 4.89) (envelope-from ) id 1eu1X0-0003Ly-GN for pgsql-sql@lists.postgresql.org; Thu, 08 Mar 2018 19:48:50 +0000 Received: from [195.159.176.226] (helo=blaine.gmane.org) by makus.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA1:256) (Exim 4.89) (envelope-from ) id 1eu1Wt-0006HE-JI for pgsql-sql@postgresql.org; Thu, 08 Mar 2018 19:48:49 +0000 Received: from list by blaine.gmane.org with local (Exim 4.84_2) (envelope-from ) id 1eu1Un-0007Y3-DT for pgsql-sql@postgresql.org; Thu, 08 Mar 2018 20:46:33 +0100 X-Injected-Via-Gmane: http://gmane.org/ To: pgsql-sql@postgresql.org From: Thomas Kellerer Subject: Re: Query question Date: Thu, 8 Mar 2018 20:48:35 +0100 Lines: 29 Message-ID: References: <415803152.48510563.1520535505737.JavaMail.zimbra@rglholdings.com> Mime-Version: 1.0 Content-Type: text/plain; charset=utf-8; format=flowed Content-Transfer-Encoding: 8bit X-Complaints-To: usenet@blaine.gmane.org User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.8.1.21) Gecko/20090302 Thunderbird/2.0.0.21 Mnenhy/0.7.5.666 In-Reply-To: <415803152.48510563.1520535505737.JavaMail.zimbra@rglholdings.com> Content-Language: de-DE X-Host-Lookup-Failed: Reverse DNS lookup failed for 195.159.176.226 (failed) List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Precedence: bulk Stanton Schmidt schrieb am 08.03.2018 um 19:58: > My question is: > I have a table that has log events for pieces of equipment.  For each piece of equipment this table may contain 1 or more (hundreds potentially). > I need to write a query that will return only the last 5 log events for each (and every) piece of equipment. > > log_table ( > equipment_id character(30), > log_date date, > log_time time, > event_desc text > ) Queries like that are typically solved using window functions: select * from ( select equipment_id, log_date, log_time, event_desc, row_number() over (partition by equipment_id order by log_date desc, log_time desc) as rn from log_table ) t where rn <= 5; Unrelated, but: why aren't you storing "log_date_time" in a single timestamp?