在最常见的列表中查找值的排名

Finding the rank of a value in a most common list

我有一个数据库 table 包含一些名字和一些数字,如下所示:

first last    number
max   muster  1
max   juster  2
max   huster  3
jen   muster  4
jen   jenker  5
ian   hoster  6
...

我通过以下方式查询最常见的名字:

SELECT first, COUNT(*) AS value FROM table
GROUP BY first
ORDER BY COUNT(*) DESC
LIMIT 3

我想知道这个数据库 table 的名字 'ian' 的排名。在这种情况下,它是第三个常见的名字,上面的查询给了我以下内容:

    first value
1   max   3
2   jen   2
3   ian   1

我想要的是以下代码:

    first value
3   ian   1

或类似的东西,这样我就可以通过给出 first='ian' 来达到数字“3”,因为它是我的 table 中的第三个通用名称。怎么查询呢?

示例:

SELECT first, COUNT(*) AS value FROM table
GROUP BY first
ORDER BY COUNT(*) DESC

# So far we ordered the list from most common to least common

FILTER WHERE first='ian'

# We filtered the other names so that only first='ian' stays in the query,
# and we did not lose the index value (in this case 3) of the 'ian'

当然这是行不通的,但我想你明白我在寻找什么。

您可以使用 window 函数:

select *
from (
    select first_name, count(*) as cnt, rank() over(order by count(*) desc) as rn
    from mytable
    group by first_name
) t
where first_name = 'ian'

这给了你“伊恩”的等级。

你可以这样做: (适用于 PostgreSQL)

SELECT * from
(
  select ROW_NUMBER() over (ORDER BY value desc) AS rownumber, firstname, value
  from
  (
    SELECT firstname, COUNT(*) AS value
    FROM public.people as pp
    GROUP BY firstname
  ) as goo
) AS foo
WHERE foo.firstname like 'ian%';

这给出了预期的结果:

3   ian                     1

或者如果您想获得第三个结果:

SELECT * from
(
  select ROW_NUMBER() over (ORDER BY value desc) AS rownumber, firstname, value
  from
  (
    SELECT firstname, COUNT(*) AS value
    FROM public.people as pp
    GROUP BY firstname
  ) as goo
) AS foo
WHERE rownumber = 3

或者如果你想像这样限制中间结果:

SELECT * from
(
  select ROW_NUMBER() over (ORDER BY value desc) AS rownumber, firstname, value
  from
  (
    SELECT firstname, COUNT(*) AS value
    FROM public.people as pp
    GROUP BY firstname
    ORDER BY COUNT(*) desc
    limit 3
  ) as goo
) AS foo
WHERE rownumber = 3

这给出了预期的结果:

3   ian                     1