使用SQL查询如何获取两个单独的MAX值?

时间:2018-10-30 20:02:38

标签: mysql

我正在使用标准的婴儿名字数据集。我有一栏列出姓名,频率和性别。我想在一个查询中同时获得男性和女性的姓氏。我可以通过单个查询轻松地做到这一点,但是如何只用一个查询呢?

SELECT names,sex,MAX(frequency) from babynames WHERE year=1973 and sex='M';

我将如何扩展该名称,使之成为每年M和F最受欢迎的名字?

2 个答案:

答案 0 :(得分:1)

很容易获得一种性别的最常用名字:

SELECT names, sex, frequency from babynames WHERE year = 1973 and sex = 'M'
ORDER BY frequency DESC
LIMIT 1

要获得两个名称,请在UNION ALL中输入“ F”性别。

类似的东西:

select * from
(
SELECT names, sex, frequency from babynames WHERE year = 1973 and sex = 'F'
ORDER BY frequency DESC
LIMIT 1
)
UNION ALL
(
SELECT names, sex, frequency from babynames WHERE year = 1973 and sex = 'M'
ORDER BY frequency DESC
LIMIT 1
)

答案 1 :(得分:1)

一种方法使用相关的子查询:

select bn.*
from babynames bn
where bn.year = 1973 and
      bn.frequency = (select max(bn2.frequency)
                      from babynames bn2
                      where bn2.sex = bn.sex and bn2.year = bn.year
                     );