连续查找重复项

时间:2018-08-07 20:46:07

标签: sql postgresql sorting

我希望通过查看一列并仅返回该列中具有一定范围内重复值的行(在10-600个重复之间)来对一些数据进行排序。使用计数功能时,我可以看到例如:

fruits | count
-------+------
apple  |    15
banana |    23
orange |    19

我正确的代码显示了10-600个重复项之间的所有结果,但是我想查看重复的每一行。因此,我想查看15个苹果行,23个香蕉行和19个橙色行,但在我的情况下,我需要分解成千上万个“水果”,因此仅选择一个就行了。有什么想法吗?

谢谢。

2 个答案:

答案 0 :(得分:1)

您可以使用window函数:

select t.*
from (select t.*,
             count(*) over (partition by fruit) as cnt
      from t
     ) t
where cnt between 10 and 600;

答案 1 :(得分:0)

您可以使用窗口功能(https://www.postgresql.org/docs/9.1/static/functions-window.html

create table fruits (id SERIAL PRIMARY KEY, name varchar(255));

insert into fruits (name) values ('apple'), ('banana'), ('orange'),
('apple'), ('banana'), ('orange'),('apple'), ('banana'), ('orange'),
('apple'), ('banana'), ('orange'), ('pear');

select
    id,
    name
from (
    select
        count(*) over (partition by name) as total,
        id,
        name
    from fruits
) as t
where t.total >= 1 and t.total <= 6;
相关问题