Select max value in subquery in SQL

2019-03-03 17:38发布

问题:

I have a query like below:

select * 
from 
    (select 
         centre_name, sum(qty) as number1 
     from 
         (select 
              exchange_from_centre_id as cenid, 
              count(exchange_from_centre_id) as qty
          from 
              as2.exchange
          group by 
              exchange_from_centre_id

          union all

          select 
              exchange_to_centre_id as cenid, 
              count(exchange_to_centre_id) as qty
          from 
              as2.exchange
          group by 
              exchange_to_centre_id), as2.centre c
where 
    c.centre_id = cenid
group by 
    centre_name);

and this is the result: Name of the centre and the number of exchange

Alice Springs Desert Park   1
Werribee Open Range Zoo     6
Kruger National Park        2
Johannesburg Zoo            4
Australia Zoo               2
SanWild Wildlife Sanctuary  5

I like to select the max value from this result (the 2nd row), beside sorting and choosing the 1st row, could anyone help me with the MAX query.

回答1:

that should work

select * from (select centre_name, sum(qty) as number1 from 
                (select exchange_from_centre_id as cenid, count(exchange_from_centre_id) as qty
                from as2.exchange
                group by exchange_from_centre_id
            union all
                select exchange_to_centre_id as cenid, count(exchange_to_centre_id) as qty
                from as2.exchange
                group by exchange_to_centre_id), as2.centre c
where c.centre_id = cenid
group by centre_name) where number1 = (select max(number1) from (select centre_name, sum(qty) as number1 from 
                (select exchange_from_centre_id as cenid, count(exchange_from_centre_id) as qty
                from as2.exchange
                group by exchange_from_centre_id
            union all
                select exchange_to_centre_id as cenid, count(exchange_to_centre_id) as qty
                from as2.exchange
                group by exchange_to_centre_id), as2.centre c
where c.centre_id = cenid
group by centre_name));


回答2:

SQL Fiddle Demo

I use your result query instead of the big query to simplify the sample.

I update your sample to have 2 row with max value 6.

You calculate in a select the max value, and then join to the original table to bring all row matching that value

SELECT *
FROM (SELECT MAX(Score) Score
      FROM Table1) as mV
INNER JOIN Table1 t
   ON mv.Score = t.Score


标签: sql subquery max