Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- id name value date
- a last jones 2018-04-03 01:00:00
- a last smith 2018-04-03 03:03:03
- a last johns 2018-04-04 02:02:02
- b last johns 2018-04-03 12:12:12
- b last smith 2018-04-04 03:03:03
- c last smith 2018-04-03 11:11:11
- c last johns 2018-04-03 17:17:17
- c last jones 2018-04-05 01:01:01
- SELECT distinct a.id
- FROM people a
- left JOIN people b
- ON (a.id = b.id and a.name=b.name and a.date < b.date)
- where b.date is null
- and a.name = 'last'
- and a.value = 'johns';
- id
- --
- a
- id
- --
- b
- c
- create table people
- ( id char(1) not null
- , name char(4) not null
- , value varchar(20) not null
- , ts timestamp not null);
- insert into people (id, name, value, ts)
- values ('a', 'last', 'jones', '2018-04-03 01:00:00')
- , ('a', 'last', 'smith', '2018-04-03 03:03:03')
- , ('a', 'last', 'johns', '2018-04-04 02:02:02')
- , ('b', 'last', 'johns', '2018-04-03 12:12:12')
- , ('b', 'last', 'smith', '2018-04-04 03:03:03')
- , ('c', 'last', 'smith', '2018-04-03 11:11:11')
- , ('c', 'last', 'johns', '2018-04-03 17:17:17')
- , ('c', 'last', 'jones', '2018-04-05 01:01:01');
- select id
- from people a
- where not exists (
- select 1
- from people b
- where a.id = b.id
- and a.name=b.name
- and a.ts < b.ts
- )
- and a.name = 'last'
- and a.value = 'johns';
- select id
- from people a
- where not exists (
- select 1
- from people b
- where a.id = b.id
- and a.name=b.name
- and a.ts < b.ts
- and b.ts < '2018-04-04 00:00:00'
- )
- and a.name = 'last'
- and a.value = 'johns'
- and a.ts < '2018-04-04 00:00:00';
Add Comment
Please, Sign In to add comment