小编典典

在SQL的子查询中选择最大值

sql

我有一个如下查询:

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);

结果如下:中心名称和交换数量

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

我喜欢从此结果(第二行)中选择最大值,除了排序和选择第一行之外,还有谁能帮助我进行MAX查询。


阅读 133

收藏
2021-04-14

共1个答案

小编典典

那应该工作

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));
2021-04-14