简体   繁体   English

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

[英]Select max value in subquery in SQL

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

SQL Fiddle Demo SQL小提琴演示

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. 我将样本更新为2行,最大值为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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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