Mysql select one last row of each type

I have a table with id, TYPE, NUMBER, DATE

example, no date:

1 a 15
2 c 10
3 b 11
4 b 14
5 a 19
6 c 1
7 b 14
8 b 7

SELECT 1:

I want to select 1 last record of each type ... so the result will be:

5 a 19 15.2.2014 16:00
8 b 7 15.2.2014 16:50
6 c 1 15.2.2014 17:00

NOW it is 02.15.2014 17:01

SELECT 2:

I want to select the maximum of "SELECT 1" from each last type in the last 60 minutes (try not to do this as "select from (SELECT 1)", the result will be:

8 b 7 15.2.2014 16:50

Can someone help me?

+4
source share
4 answers

You can do the first with this sentence exists:

select t.*
from table t
where not exists (select 1
                  from table t2
                  where t2.type = t.type and t2.date > t.date
                 );

60 . 60 , where:

select t.*
from table t
where t.date >= date_sub(getdate(), interval 1 hour) and
      not exists (select 1
                  from table t2
                  where t2.type = t.type and t2.date > t.date
                 );

, , date. id.

+3
SELECT id,type,date from table 
WHERE 
id in (SELECT max(id) FROM table GROUP BY type);
+3

Try the following:

select *
from Table1
where id in (select max(id) from Table1 group by type)

fiddle

+2
source

you can do this with this query

(SELECT * FROM example WHERE type="a" ORDER BY ID DESC LIMIT 1)
UNION
(SELECT * FROM example WHERE type="b" ORDER BY ID DESC LIMIT 1)

EDIT This code is checked and works

0
source

Source: https://habr.com/ru/post/1527098/


All Articles