简体   繁体   中英

Select Min and Max value

I have a table called 'customers':

id | name    | age

1  | john    | 35        
2  | paul    | 22        
3  | ana     | 26   
4  | mark    | 19   
5  | jack    | 29   

i want to select the name and max age, the name and min age... something like:

john 35 mark 19

is it possible?

The below query will give you the min and max on one row as requested. If there are multiple matches for min/max you will get multiple rows. Depending on the SQL engine you use, the syntax to limit to one row is different.

SELECT cMax.Name, cMax.Age, cMin.Name, cMin.Age
FROM customers cMin
JOIN customers cMax ON
    cMax.Age = (SELECT MAX(Age) FROM customers)
WHERE cMin.Age = (SELECT MIN(Age) FROM customers)

There are different types of joins (eg INNER, OUTER, CROSS); however, for your question it doesn't much matter which you use.

try this

    select name, age from customers where age=(select max(age) from customers) union
 select name, age from customers where age=(select min(age) from customers) 

Yes, you can do it,

select name, age from customers
where age in (select max(age) 
from customers union select min (age)from customers)

If you want them on the same row:

select cmin.*, cmax.*
from (select name, age as minage
      from customers
      order by age asc
      fetch first 1 row only
     ) cmin cross join
     (select name, age as maxage
      from customers
      order by age desc
      fetch first 1 row only
     ) cmax;

fetch first 1 row only is standard syntax for returning only the first row of the result set. Some databases have bespoke syntax, such as limit or select top (1) .

Try using this query to show MAX age:- select * from customers where age=(select max(age) from customers);

To show MIN age use the below Query:- select * from customers where age=(select min(age) from customers);

You could use a cross join , which will put the two query ouputs next to one another. Building off Rodrigo's queries:

select
  max_cust.name,
  max_cust.age,
  min_cust.name,
  min_cust.age
from (select name, age from customers where age=(select max(age) from customers)) as max_cust
cross join (select name, age from customers where age=(select min(age) from customers)) as min_cust

It's maybe not the most performant but it gets the right shape. Be wary of cross joins when the tables don't have exactly 1 row, as it creates a cartesian product of the rows in the tables being joined.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM