从一系列日期中获取所有前5个id(数组)

时间:2015-10-13 14:41:22

标签: sql postgresql postgresql-8.1

我需要查询tableA中的前5个值。如下面

    select id, count(occurrence), date 
    from 
    (select id, unnest(value) as occurrence, date from tableA) as a
    group by id, occurrence, date 
    order by occurrence desc 
    limit 5

 id  | occurrence |   date   
-----+-------+----------
 330 |    11 | 20141015
 400 |    11 | 20141015
 390 |    10 | 20141015
 240 |    10 | 20141015
 501 |    10 | 20141015

并在收到ID后,查询同一个tableA以获取其他日期范围的所有值,范围从20140101到20141015。

expected result:

 id  | occurrence |   date   
-----+-------+----------
 330 |    11 | 20141015
 400 |    11 | 20141015
 390 |    10 | 20141015
 240 |    10 | 20141015
 501 |    10 | 20141015
 330 |    0  | 20141014
 400 |    1  | 20141014
 390 |    10 | 20141014
 240 |    15 | 20141014
 501 |    10 | 20141014
 330 |    11 | 20141013
 400 |    11 | 20141013
 390 |    11 | 20141013
 240 |    19 | 20141013
 501 |    10 | 20141013

但我怎么能这样做呢?

我的postgresql版本是8.1,我不能使用分区(如果有任何想要建议的话)

修改

select  id, count(value) as occurrence, date
from tableA
where id = ANY(
    select array(
        select id
        from (
            select date, unnest(id) as id
            from tableA where date>='20140101' and date<='20141015'
            )as a
        )
)
group by id, date

不会返回任何内容。我的数组是否正确?

2 个答案:

答案 0 :(得分:0)

您可以尝试从表格中选择某人,其中dt&gt; 20140101和dt&lt; 20141015和row_num&lt; = 5这将为您提供正确的答案。

答案 1 :(得分:0)

Year    Month    Rain
1890      1       80.5
1890      2       72.4
1890      3       66.8
1890      4       77.2