【问题标题】:Get all top 5 id(an array) from a range of dates从一系列日期中获取所有前 5 个 id(一个数组)
【发布时间】:2015-10-13 14:41:21
【问题描述】:

我需要从 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

收到ids后,查询同一个tableA,获取20140101到20141015其他日期的id的所有值。

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

不返回任何内容。我的数组正确吗?

【问题讨论】:

    标签: sql postgresql postgresql-8.1


    【解决方案1】:

    你可以尝试 select sth from table where dt > 20140101 and dt

    【讨论】:

    • 你能告诉我们更多细节吗?你到底想要什么?
    • id 是一个数组,如果你注意到了
    【解决方案2】:
    select id, count(value) as occurrence, date
    from t
    where id in (
        select id
        from (
            select id, count(value) as occurrence, date 
            from t 
            group by id, date 
            order by occurrence desc 
            limit 5
        ) s
    ) q
    group by id, date
    

    【讨论】:

    • 我认为我们不需要将所有 IN () 都命名为 q??
    • value 实际上是一个数组。抱歉,我已经编辑了我的问题。提前致谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-21
    • 1970-01-01
    • 2016-01-11
    • 2021-03-30
    • 2016-01-26
    • 2023-03-14
    • 1970-01-01
    相关资源
    最近更新 更多