简体   繁体   English

如何选择列中第二频繁的值?

[英]How to select the second most frequent value in column?

Could you please help me with this select query?你能帮我解决这个选择查询吗?

countries table in DB AS photo DB AS 照片中的国家/地区表

I need to select the most second frequent (duplicated) country in the column我需要在列中选择第二频繁(重复)的国家

Output should be like this: IT输出应该是这样的: IT

SELECT name
FROM Countries
GROUP BY name
ORDER BY count(name) DESC
LIMIT 1,1;

There might be shorter and simpler queries, but this one should work on every DB and prevent issues like the key words LIMIT , TOP etc. can't be used on all different DB's.可能会有更短更简单的查询,但是这个查询应该适用于每个数据库,并防止关键字LIMITTOP等问题不能在所有不同的数据库上使用。

SELECT name FROM Countries
GROUP BY name
HAVING COUNT(name) = (SELECT MAX(a.amount) AS amount
FROM (SELECT name, COUNT(name) AS amount
FROM Countries
GROUP BY name) a
WHERE amount < (SELECT MAX(b.amount) FROM
(SELECT name, COUNT(name) AS amount
FROM Countries
GROUP BY name)b));

This query will find step by step the second frequent value of your table using sub queries.此查询将使用子查询逐步找到表的第二个频繁值。

Hello you can use this also你好你也可以用这个

with flo as (
select country , count(*)as cate, dense_rank()over( order by count(*)  desc)as rnk
from yourtable
group by country)
select country from flo 
where rnk=2

i wrote now this query and it worked well too :)我现在写了这个查询,它也很好用:)

SELECT name FROM Countries GROUP BY name HAVING count(name) = (
SELECT a.amount from (
SELECT DISTINCT COUNT(name) as amount FROM countries GROUP BY name ORDER 
by amount DESC limit 1,1) a  )

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

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