Select max value in subquery in SQL

假装没事ソ 提交于 2019-12-20 06:39:13

问题


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


来源:https://stackoverflow.com/questions/32673980/select-max-value-in-subquery-in-sql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!