sql - SELECT for recent data only

Asked

Viewed 146 times

2

I don’t think my title corresponds to doubt.

The application I develop inserts once a month, data referring to the last backup in a table. This table contains the backup instance code, the input data and the number of bytes.

The problem is that I do not know a command or way to make SQL a SELECT that brings only the last results of each backup.

Tenho isso
backup   bytes    data
'x'        30  '21/12/14'
'x2'     1200  '14/10/14'
'x2'     3500  '14/12/14'
'x2'     4800  '14/01/15'


Mas preciso somente dos últimos
backup   bytes    data
'x'        30  '21/12/14'
'x2'     4800  '14/01/15'

I am noted in SQL, but any information is already of great value.

4 answers

3


I believe something like that solves your problem:

SELECT backup, bytes, MAX(data) FROM table_name GROUP BY backup
  • Your solution worked perfectly, thank you very much! :D

  • @Haxz this solution would only work if bytes was part of the primary key which makes no sense.

2

Hi, come on:

What type is the date field? If date you can sort it by decreasing form (today is greater than yesterday and yesterday is greater than a month ago) and to limit your search you can use the function LIMIT SQL, something like that:

SELECT * FROM backup ORDER BY data DESC LIMIT 2;
  • Yes the field is date, the problem would be in this delimiting... Because the number of backups is relative to the user (one for n).

  • I will probably have to create another query to bring backups without repeating...

1

select distinct on (backup) *
from t
order by backup, data desc

1

Well I saw your question again, and the scenario below does not fit what you need... Luis' answer will better solve your problem.


I do not use Postgresql, but I believe it is something very similar to this:

SELECT * FROM sua_tabela ORDER BY data DESC LIMIT 2;

Exchange the Limit value for the amount of results you’d like to show;


Browser other questions tagged

You are not signed in. Login or sign up in order to post.