Re: Query question

From: Thomas Kellerer <spam_eater(at)gmx(dot)net>
To: pgsql-sql(at)postgresql(dot)org
Subject: Re: Query question
Date: 2018-03-08 19:48:35
Message-ID: p7s3uj$dg0$1@blaine.gmane.org
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

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?

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Stanton Schmidt 2018-03-08 20:17:58 Re: Query question
Previous Message David G. Johnston 2018-03-08 19:28:31 Re: Query question