0

So I need to print the oldest and youngest result in a table my code is

SELECT client.clientfirstname, client.clientlastname, client.clientdob
FROM client
order by (client.clientdob) DESC
FETCH first 1 row only


SELECT client.clientfirstname, client.clientlastname, client.clientdob
FROM client
order by (client.clientdob) ASC
FETCH first 1 ROW ONLY;

these 2 by themselves will return the right value but I cant get them both to run at once, it seems I cant use a Union with this setup, if possible a single select statement where I can get both the first and last would be even better. I am also using SQL developer if there is way to get both of these to show in the same SQL query result window that would be fine.

3 Answers3

1

You can try the below -

SELECT client.clientfirstname, client.clientlastname, client.clientdob
FROM client where 
client.clientdob=(select max(client.clientdob) from client)
or 
client.clientdob=(select min(client.clientdob) from client)
Fahmi
  • 37,315
  • 5
  • 22
  • 31
0

You can use UNION ALL like this below:

select c1.* from (select client.clientfirstname, client.clientlastname, client.clientdob, row_number() over (order by client.clientdob ASC) as rn FROM client) c1 where c1.rn =1
union all
select c2.* from (select client.clientfirstname, client.clientlastname, client.clientdob, row_number() over (order by client.clientdob DESC) as rn FROM client) c2 where c2.rn =1
Soumendra Mishra
  • 3,483
  • 1
  • 12
  • 38
0

We can use analyitical function row_number() to get the desired result,

select *
  from
(
select cl.clientfirstname
     , cl.clientlastname
     , cl.clientdob 
     , row_number() over (order by cl.clientdob desc) max_rn
     , row_number() over (order by cl.clientdob asc) min_rn
FROM client cl
) t
where (max_rn = 1 or min_rn = 1)
Sujitmohanty30
  • 3,256
  • 2
  • 5
  • 23